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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Inheritance and friendship
- Storage Classes in C++ with Examples
- Trivial classes in C++
- C++ Classes and Objects
- Nested Classes in C++
- Local Classes in C++
- Anonymous classes in C++
- File Handling through C++ Classes
- C++ Stream Classes Structure
- How to add reference of an object in Container Classes
- Virtual functions in derived classes
- Pure Virtual Functions and Abstract Classes in C++
- Catching base and derived classes as exceptions
- Enum Classes in C++ and Their Advantage over Enum DataType
- cin get() in C++ with Examples
- std::less in C++ with Examples
- Pi(π) in C++ with Examples
- std::add_lvalue_reference in C++ with Examples
- std::is_trivially_assignable in C++ with Examples
- Map of Vectors in C++ STL with Examples