C++ Friend Functions


What is Friend Function?

  • The functions can be defined somewhere in the program just like a normal function but friend function is defined outside the class but it can still access all the private and protected members of the class.
  • If we define a function as a friend function, then the protected and private data of a class can be accessed using the function.
  • The friend can be a function, a function template or member function, a class or a class template where the entire class and all the members of the class are friends.
  • It is easy to declare the friend function. The keyword friend is used while declaring the friend function.

Synatx for declaring the friend function:

class class_name

friend data_type function_name()  ;


Friend function example:

Let us have a look at the example to better understand the friend function:

In the above program, the friend fucntion printArea( ) is declared inside Shape class. So, the private data can be accessed from this function.

Some points to Remember:

  • Friend function can be invoked like a normal function without the help of any object.
  • It cannot access the member names directly and to access them it has to use object name and dot operator with each member name (B.x).
  • Friend function can be declared either in public or private class.

Friend Class

  • The friend class can access the private and protected members of other class in which it is declared as friend.
  • It is also useful to allow a particular class to access the private members of other class.


Like it? Please Spread the word!