C++ – ‘Friend’

A class or a function can be made a friend of another class in C++. A friend gets access to all the private members and protected members of the class to which it becomes a friend.

A friend function will need to be declared inside the class to which it becomes a friend. But this function will not be a member function of the class. In the below example, getName() is declared as a friend of Animal and as a result, getName() gets access to the private members of this class.

class Animal{
    string name;

    public:
    Animal();
    friend string getName();
};

A friend function can be defined within the class or outside of the class (to which it becomes a friend). It can be defined outside of the class just like any other global function. A friend function can also be a member function of another class. Please note that a friend function of a base class is never inherited by a derived class.

A friend class is just another class that is declared as a friend of some class. Like friend function, it will also need to be declared within the class to which it becomes a friend. In the below example,  FriendOfAnimal is declared as a friend of Animal and therefore has access to all the private and protected members of Animal. Like a friend function, a friend class of a base class is never inherited by a derived class.

class FriendOfAnimal{
    ......
};

class Animal{
    string name;

    public:
    Animal();
    friend class FriendOfAnimal;
};

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s