Friend Function
A function which is not member of the class but which can access the members of the class is known as a friend function.
To declare a friend function, we have to include its prototype within the class preceding it with the keyword “friend”.
e.g.
#include < iostream.h > class complex { private: float a,b; public: void getdata(); void display(); friend complex sum(complex,complex); }; void complex :: getdata() { cin>>a>>b; } void complex :: display() { cout << a << b; } // definition of friend function complex sum(complex c1,complex c2) { complex temp; temp.a = a + c1.a; temp.b = b + c1.b; return(temp); } void main() { complex c1,c2,c3; c1.getdata(); c2.getdata(); c3 = sum(c1,c2); //calling function sum c3.display(); } |
Friend Class:
It is possible for one class to be a friend of another class. When this is the case, the friend class and all of its member functions have access to the private members defined within the other class.
For example:
// Using a friend class
#include < iostream.h > class TwoValues { Int a,b; Public: TwoValues(int i,int j) {a = i;b = j;} friend class min; }; class min { public: int min(TwoValues x); }; int min :: min(TwoValues x) { return x.a < x.b ? x.a : x.b; }; main() { TwoValues ob(10,20); min m; cout << m.min(ob); } |
Note: In the above example class min has access to the private variables a and b declared within the TwoValues class.
CACKLE comment system