Introduction to Friend Function

 

Friend Function

The private data is not accessible outside the class.

To access the private data we use the friend function.

A friend function is not a member function of the class.

A friend function can be invoked without using an object.

The argument passed in the friend function is used as its object.

friend return_type

function_name(class_name object)

 

Eg:-


#include <iostream>
using namespace std;

class frnd
{
private:
   int a,b;
public:

   void input()
    {
     cout<<"Enter the value of a and b\n";
     cin>>a>>b;
    }

  friend int compute(frnd f1);
};

 int compute(frnd f1)
{
  int x=f1.a+f1.b;
  return x;
}

int main()
{
  frnd f;
  f.input();
  cout <<"The result is: "<< compute(f)<<"\n";
return 0;
}

Output:-   Enter the value of a and b

5

6

The result is: 11

0 Comments