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 :

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

Output :

Enter two values:
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 :