The Basic object-oriented concepts of data hiding and encapsulations are implemented by restricting non-member functions from accessing an object’s private data. The basic policy is, if you are not a member then you cannot get in. Private data values cannot be read or written to by non-member functions. Sometimes this rigid rule for isolating data from function can be inconvenient. Imagine that you want a function to operate on objects of two different classes. Perhaps the function will take objects of the two classes as arguments, and operate on their private data. Of course this is not possible since a function cannot be a member of two classes. What we need is a means to allow a function access to the private members of a class without requiring membership. A non-member function that is allowed access to the private variable of a class is called a friend of the class.
friendvoid display (person abc);
Voiddisplay (person abc) //friend function without :: operator
Note: The keyword friend is not repeated in the function definition.
The friend function in the example could perhaps have the same operation if it were a member function of the class. However if the same function needed to access objects from different classes it would be most useful to make it a friend of the different classes.
There are some features of a friend function that are worth remembering:-
- A friend function can access the private members of a class.
- Friend functions need not have a ‘this’ pointer, as it does not belong to any object.
- The friend declaration is unaffected by its location in the class.
- The definition of a friend function does not require the class name with the scope resolution operator prefixed to it, as it is required for a class ember function.
Only when a function access private members of two or more class directly, it has to be declared as a friend function. Otherwise public members of a class can be accessed directly by any function. There is some controversy regarding the use of friend functions.
On one hand, friend functions increase flexibility in programming, on the other they are against the principles of object-oriented programming.
A friend function has to be declared in the class whose data it will access. This cannot be done if the source code is not available to a programmer. If the source code is available, then existing classes should not be modified as far as possible. If you intend to use friend functions the class should be designed as such, right from the beginning. Even then, friend functions are not a tidy concept to work.
Advantages of friend functions are as follows:-
- When two or more classes contain members that are interrelated with the other parts of your program then friend functions prove to be useful.
- Friend functions many be useful in operator overloading.
- Friend functions may facilitate the creation of some type of I/O functions.
For more go through this video:-