What is the usage of ‘friend’ in C++?

In C++, the friend keyword is used to allow other classes or functions to access the private members of a class. These authorized classes or functions are referred to as friend classes or friend functions.

By using the friend keyword, we can declare other classes or functions as friends within the definition of a class, allowing these friend classes or functions to access the private members of that class (private members include private variables and functions).

The declaration of friend function is:

class MyClass {
    friend void friendFunction();
};

The declaration method for a friend class is:

class MyClass {
    friend class FriendClass;
};

All member functions of a friend class have access to the private members of the declaring class.

It is important to note that friendship in C++ is one-way. If class A declares class B as a friend, class B does not automatically declare class A as a friend. If bi-directional access is needed, each class must declare the other as a friend separately.

Use friendship sparingly as it can compromise encapsulation. Only use it when it is absolutely necessary for other classes or functions to access private members.

bannerAds