Sometimes, there is a need for allowing a particular class to access private or protected members of a class. The solution is a friend class, which is capable of accessing the protected as well as the private members of the class in which it is declared as a friend.
Similarly to the friend class, a friend function is able to access private and protected class members. A friend function can either be a global function or a method of some class.
Some important points about friend class and friend function:
- Friendship is not inherited
- Friendship isn’t mutual i.e. if some class called Friend is a friend of some other class called NotAFriend then it doesn’t automatically become a friend of the Friend class
- The total number of friend classes and friend functions should be limited in a program as the overabundance of the same might lead to a depreciation of the concept of encapsulation of separate classes, which is an inherent and desirable quality of object-oriented programming.