Friend function in C++

Friend keyword is used for friend functions.

In C++ class has data member and member function. Data member declare private that cannot be accessed outside the class, means non-member function of class. But some time situation is arises, private data member need to access outside the class. That is done by friend function. A friend function is called non-member function, when we create friend function, we can access private member of class.

#include<iostream.h>

#include<conio.h>

class xyz

{

private:

   int x;

friend void disp();  //friend function

};

void disp()

{

xyz obj;

obj.x=5;  //access the variable

cout<<"the value of x="<<obj.x;  //print the value

}

void main()

{

disp();  //calling function

getch();

}

friend function

Explaination….

In this example we create a disp(),which is private. But the function is friend means we can access outside the class. Friend function access the class variable x by using dot operator.By using friend functions ,the member function of one class can be accessed by another class.