Mutual friendship of Classes in C++ with Examples
Prerequisite: Friend Class in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private members of another class.
Below is the program to illustrate the friend class:
Accessed Private Member of class A A::a = 0
Mutual Friendship of Classes: For class A and B is said to be in mutual friendship if class A is a friend class of class B and class B is a friend class of class A. Due to the establishment of friendship between these two classes, both the classes can access each other protected and private members using their own member functions.
Proceeding normally to declare and define functions within both of these classes, there will be a common syntax error is encountered, which signals that the class declared first cannot access the data members of the succeeding class even when made a friend.
Therefore Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of class A automatically.
But we can make the mutual friendship of classes by avoiding error occurred above, the functions in the first class which is accessing the data members of the second class are defined after the second class using a scope resolution operator.
Let us assume class A was defined first in the program and class B was defined after class A. The member functions in class A accessing the data of class B should be defined after class B. This is done to make sure that the compiler first reads class B which in turn will provide the information to the compiler that class A is a friend of class B, and hence is allowed to access its members.
Below is the program to illustrate mutual friendship of classes:
Data of A is: 10 Data of B is: 20
In the above program as class A and class B are mutual friends. Therefore, for accessing the private member of class A can also be done from member function in class B and for accessing the private member of class B can also be done from member function in class A.