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.

Example:

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.

Output

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.

Output

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

Leave a Reply

Close Menu