The C++ friend Keyword


The friend keyword allows you to designate a function or another class as a friend of your class. A friend of a class has direct access to the private and protected members of the class, eliminating the need to call accessor and mutator methods.

This can speed up your code by removing the overhead of those accessor method calls. However, your class and its friend are now more tightly coupled, which means that a change to the class will probably also require a change to its friend.

friend Functions

To make a function a friend of your class, code a friend declaration for the function anywhere inside your class definition. The friend function will be able to directly access the private and protected members of your class, with no need to call set/get methods.

A friend declaration for a function consists of the function's prototype, preceded by the friend keyword.

For example:

class Alpha
{
    // Declares the overloaded operator<<() function to be a friend of class Alpha.
    friend std::ostream& operator<<(std::ostream&, const Alpha&);

    ...
};

friend Classes

To make another class a friend of your class, code a friend declaration for the class anywhere inside your class definition. Any method of the friend class that has access to an object of your class will be able to directly access its private and protected members.

A friend declaration for a class takes the form friend class ClassName.

For example:

class Alpha
{
    // Declares the class Beta to be a friend of class Alpha.
    friend class Beta;

    ...
};

Restrictions on the friend Keyword