Friend Function in C++

The function which is made as friend to the existing function has all the access to the data members of that parent function.

Source code :

#include<iostream>
using namespace std;
class parent
{
    int val1,val2;
   public:
    void get()
    {
       cout<<"Enter two values:";
       cin>>val1>>val2;
    }
    friend int sum(parent object);
};
int sum(parent object)
{
   return int(object.val1+object.val2);
}
int main()
{
    
    parent obj;
    obj.get();
    cout<<"\n The sum is : "<<sum(obj);
    return 0;
}          

Output :

Enter two values:
2
3
The sum is : 5

Algorithm :

  1. Get the two numbers using a function .
  2. Declare an other function using friend keyword within the same class.
  3. Define the function wherever you want(outside that class).
  4. Call the first function alone written to get the values and you can see the friend function also get executed.

Output :


                

Comments :