What is friend class in C++? Show by C++ Code example

(Last Updated On: April 10, 2017)

Answer includes friend class in C++ using a C++ code example and uses. Rather that defining it lets describe friend class by example and understand definition..


Mainly, friend class is used for encapsulation (data hiding). If we want some class to keep private variables/data visible to some specific class and don’t want it to be visible to the rest of the world. We should be using friend class as a best solution.

For example, let’s have two classes i.e class A and Class B. We want object int option” of class A to be initialized by class B’s method first and then proceed.


Friend class – C++ Program Example :