Friend classes in C++ with the examples

In C++ like the friend function, we have friend classes also. By using the keyword “friend” it is possible to make the class a friend to another class. If we make the class a friend class, the member functions that are available in the class will become friends to another class.
Below is the syntax of the friend class. Here is one condition that  the friend becoming class must be first declared or defined

In the above code sample, all member functions of class ClsSecond will be friend function of class ClsFirst. So we can access any member function of the ClsSecond can access the private and protected data of class ClsFirst.

If ClsSecond is declared friend class of ClsFirst then, all member functions of class ClsSecond can access private data and protected data of class ClsFirst but, member functions of class ClsFirst cannot private and protected data of class ClsSecond.

In addition to this, we are having the access to private members, friend classes will also have access to any protected members of the class.

Below is the small example that can help us to understand the friend classes usage:

We declared ClsSecond as a friend of ClsFirst so that ClsSecond member functions could have access to the private member, ocFirst.iPrivateVal

In our example, ClsSecond is considered as a friend class by ClsFirst but ClsSecond does not consider ClsFirst to be a friend, so ClsSecond can access the private members of ClsFirst but not the other way around.

The benefits of friend classes:

There may be some situations we want to iterate the linked list through a separate class. In this situation, we need to access the private data member of the list class. At this time, we need to make the class that needs to access the private data of the class list be friend to the list class.