Mutual Friendship of Classes in C++

Here in this tutorial, we will learn about what is Mutual Friendship in classes and how it can take place with the C++ code example. It is one of the most famous concepts in Object-Oriented Programming. If there are various classes, they can easily interact with each other. If classes have Mutual Friendship, they can easily access each other’s private and Protected members too.

Concept of Mutual Friendship:

For instance, let’s say there are two classes- Class A and Class B. Now if Class A is the friend of Class B and Class B is also the friend of Class A, then only we can say they have Mutual Friendship. By Mutual Friendship, both classes can access each other’s private and protected members easily. It is not necessary that only two classes can have Mutual Friendship, it can be between more than 2 classes also. 

Friend Function:

A Friend function is used to access the Private and Protected members of other classes where we declare it as a friend. It allows a particular class to access even the Private members of other classes. However, Friend function can be declared in any part.
Access Specifiers are not written with it. It is just used to show friendship in classes. It does not matter whether it is a private or a public member. This is not a caller. This function has objects as arguments. It can access members of the class by its objects.

Below is our C++ code for the mutual friendship of Classes.
#include<iostream>
using namespace std; 
class Num 
{ int a,b; 
public: 
void get( int m, int n) 
{
 a=m;
b=n;
}
friend int sum(Num s); 
}; 

int sum(Num s) 
{ return int(s.a+s.b);
} 
int main() 
{ Num s;
s.get(5,6);
cout<< "The sum is"<< sum(s); 
} 

On compiling and executing we get the output for the above code :

The sum is11

So in the above code, we can see how we used the Friend Function and used it to access the members of class outside it. We can see that we made objects to access the members of the class using the Friend. Firstly, we must understand that Friendship is not automatic. It happens only when the Friend function is there. Secondly, it is not mutual on its own. We do it forcefully. Moreover, we cannot inherit Mutual Friendship. So this friend can be :

  • function
  • function template
  • member function
  • class or class template, where the whole class with all its members are friends.

Concluding the tutorial, we can say we have learned about Mutual Friendship in this tutorial. We learnt how C++ provides us with this advantage. This concept if cleared can make our work much more easy and versatile. 

Leave a Reply

Your email address will not be published. Required fields are marked *