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:
CPP
#include <iostream>
using namespace std;
class A {
private :
int a;
public :
A() { a = 0; }
friend class B;
};
class B {
private :
int b;
public :
void showA(A& x)
{
cout << "Accessed Private "
<< "Member of class A\n" ;
cout << "A::a = " << x.a;
}
};
int main()
{
A a;
B b;
b.showA(a);
return 0;
}
|
Output:
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:
CPP
#include <iostream>
using namespace std;
class B;
class A {
int data;
public :
friend class B;
A( int d) { data = d; }
void get_data_B(B objb);
};
class B {
int dataB;
public :
friend class A;
B( int d) { dataB = d; }
void get_data_A(A obja)
{
cout << "Data of A is: "
<< obja.data;
}
};
void A::get_data_B(B objb)
{
cout << "Data of B is: "
<< objb.dataB;
}
int main()
{
A a(10);
B b(20);
b.get_data_A(a);
cout << endl;
a.get_data_B(b);
return 0;
}
|
Output:
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.
Last Updated :
16 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...