Friend Functions and Friend Classes in C++

We have been emphasizing that the private members cannot be accessed from outside the class. That is, a non-member function cannot have an access to the private data of a class. However, there could be a situation where we would like two classes to share a particular function. For example, consider a case where two classes, manager and scientist, have been defined. We would like to use a function income() to operate on the objects of both these classes. In such situations, C++ allows the common function to be made friendly with both the classes, thereby allowing the function to have access to the private data of these classes. Such a function need not be a member of any of these classes. To make an outside class “friendly” to a class, we have to simply declare this function as a friend of the class as illustrated below: class ABC {...