Friend Keyword in C++ allow functions which are not the part of the class (i.e non-member function) and other classes to access the private as well as public data members of the class in which it has been declared as a friend.


Friend keyword can be used with function and class as well. This means if a class is declared as a friend it has access to all data members (private & public) of class which has declared it as a friend.

Let’s see both of them in action.

Friend Function in C++

The function which you are declaring as a friend should not be a member of its class. Also, it must have one of its function parameters as a class reference because that’s the only way through which you can access anything inside the scope of that class.


Friend Class in C++

If a class is declared as a friend then the all the data members of the class which has declared friend are accessible inside the whole class.


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

  • Friendship mush be GRANTED not TAKEN. Declare friendship explicitly using friend keyword.
  • Friendship is NOT SYMMETRIC. If A is a friend of B then it doesn’t imply that B is friend of A. If you want this to happen then declare explicitly in both the classes for other class.
  • 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.
  • If you have any doubts or suggestion then comment below.

Leave a Reply