What is the difference between friend function and friend class in C++3 min read

Friend Functions

A friend function is a non-member function which can access the private and protected members of a class. To declare an external function as a friend of the class, the function prototype preceded withfriend keyword should be included in that class. Syntax for creating a friend function is as follows:

Following are the properties of a friend function:

  • Friend function is a normal external function which is given special access to the private and protected members of a class.
  • Friend functions cannot be called using the dot operator or -> operator.
  • Friend function cannot be considered as a member function.
  • A function can be declared as friend in any number of classes.
  • As friend functions are non-member functions, we cannot use this pointer with them.
  • The keyword friend is used only in the declaration. Not in the definition.
  • Friend function can access the members of a class using an object of that class.

Following program demonstrates using a friend function:

Output of the above program is as follows:

In the above program show_details() function was able to access the private data member name as it is a friend of Student class.

Friend Class

A friend class is a class which can access the private and protected members of another class. If a class B has to be declared as a friend of class A, it is done as follows:

Following are properties of a friend class:

  • A class can be friend of any number of classes.
  • When a class A becomes the friend of class B, class A can access all the members of class B. But class B can access only the public members of class A.
  • Friendship is not transitive. That means a friend of friend is not a friend unless specified explicitly.

Following program demonstrates a friend class:

Output for the above program is as follows:

In the above program class B has been declared as a friend of class A. That is why it is able to access private member x of class A.

Leave a Comment