C++ TUTORIALS

FRIENDLY FUNCTIONS

We have seen till now that a non-member function cannot access the private members of a class. But it is possible using friend function.To make a function "friendly" to a class, we have to declare it as the friend of the class using friend keyword.For eg. :

	
class abc { ...... ...... public: ...... ...... friend void xyz(); //function declarartion }
The friend function can be defined anywhere in the program like a normal C++ function.The function defination does not consists of keyword friend.Friend function has the following properties:
  1. It is not in the scope of the class.
  2. It can be invoked like a normal function without use of object.
  3. It can access the private members of the class using object and dot operator.
  4. It can be declared in either private or public section.
  5. It has usually objects as arguements.
#include <iostream> using namespace std; class book { int a,b; public: void set() { a=20; b=90; } friend float mean(book b1); }; float mean(book b1) { return float (b1.a+b1.b)/2.0; } int main() { book b2; b2.set(); cout<<"mean= "<< mean(b2); return 0; }

Member functions of one class can also be used as friend function of another class.The defination of such functions is as follows:

	
class X { .... .... int fun(); }; class Y { ..... ..... friend int X :: fun(); // fun() of X is friend of Y ..... };

FRIEND CLASS

We can also declare a class as a friend of another class.If class ABC is declared as the friend class of class XYZ, all the member functions of class ABC can access the privatemembers of class XYZ.

	
class ABC; class XYZ { .... ... public: ...... friend class ABC; };