friend
KeywordThe 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.
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&);
...
};
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;
...
};
Beta
is a friend of the class Alpha
, that does not automatically make the class Alpha
a friend of the class Beta
. Friendship in C++ is not a "two-way street".Beta
is a friend of class Alpha
, and class Gamma
is a friend of class Beta
that does not automatically make class Gamma
a friend of class Alpha
. There is no such thing as a "friend of a friend" in C++.