Friend Function & Friend Class in C++

In this tutorials we will study and understand the concept & Applications of Friend Function & Friend Class in C++

Friend Function & Friend Class in C++

One of the important concepts of OOP is data hiding, i.e., a nonmember function cannot access an object’s private or protected data. But, sometimes this restriction may force programmer to write long and complex codes. So, there is mechanism built in C++ programming to access private or protected data from non-member functions. This is done using a friend function or/and a friend class.

Friend Functions in C++

A friend function of a class is defined outside that class’ scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions. A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends.

Declaration of friend function in C++
Declaration & Definition of friend function in C++
Example Program of Friend Function in C++

Run Online

Width of the box : 10
Friend Class in C++

A class can also be declared to be the friend of some other class. When we create a friend class then all the member functions of the friend class also become the friend of the other class. This requires the condition that the friend becoming class must be first declared or defined (forward declaration).

Run Online


In this program we are using the SecondClass object to access the MyClass object’s datamember and change its value. This is possible because SecondClass is a friend of MyClass

Watch it on YouTube

Leave a Reply

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