Summary: In this tutorial, we will learn about the significance of friend class and function in C++.

Friend Keyword

The Friend keyword in C++ allows a non-member (class or function) to access the private as well as public data of the class.

It is used with function and class to given them access to the class members.

For example, if class A is declared as a friend of class B, we can access all the data members (private or public) of class B from class A.

Let’s see examples of both friend function and friend class for better understanding.

Friend Function

A friend function is a function whose declaration is preceded with friend keyword inside of a class.

It accepts the reference of the class (inside which it has been declared as a friend) as an argument to access its data members.

For instance, consider the following example:


Balance: 158972
Withdraw Successful
Balance: 50072.2

In the example, we have defined the display method outside of the Account class, but have declared it as a friend function inside the same.

As a result, we were able to access and print the balance in the display method outside of the class, despite it being declared private.

Note: Although a function is the friend function, it still requires reference of the class to access its members.

Friend Class

Similar to the Friends function, we can declare another class as a friend class to give them access to data.

To grant friendship to class B, we declare the class B inside of class B preceding with the friend keywod.

Here is an example, where we have defined a class as a friend of the another class:


Withdraw Successful

In this example, we have created two class Account and DebitCard.

We have declared DebitCard as a friend class inside the Account class, so that we can access its withdraw method to debit money from the account.

Overview of Friend in C++

There are some points we should remember regarding friend in C++.

  • Friendship must be GRANTED not TAKEN. Declare friendship explicitly using the friend keyword.
  • Friendship is NOT SYMMETRIC. If A is a friend of B then it doesn’t imply that B is a friend of A. If you want this to happen then declare them as friends in both classes.
  • Friendship is NOT TRANSITIVE. If A is a friend of B and B is a friend of C then it doesn’t mean that A is a friend of C.

In this tutorial, we learned what friend function and class is and how we define and use them in C++.

Leave a Reply

10 − 8 =