Friend class
Appearance
A friend class in C++ can access the "private" and "protected" members of the class in which it is declared as a friend.[1]
Rationale
Friendship may allow a class to be better encapsulated by granting per-class access to parts of its API that would otherwise have to be public.[2] This increased encapsulation comes at the cost of tighter coupling between classes.[3]
Example
class B {
friend class A; // A is a friend of B
private:
int i;
};
class A {
public:
A(B b) {//Note that the object has to be passed as a parameter to the function
b.i = 0; // legal access due to friendship
}
};
Features
- Friendships are not symmetric – If class
A
is a friend of classB
, classB
is not automatically a friend of classA
. - Friendships are not transitive – If class
A
is a friend of classB
, and classB
is a friend of classC
, classA
is not automatically a friend of classC
. - Friendships are not inherited – A friend of class
Base
is not automatically a friend of classDerived
and vice versa; equally ifBase
is a friend of another class,Derived
is not automatically a friend and vice versa. - Access due to friendship is inherited – A friend of
Derived
can access the restricted members ofDerived
that were inherited fromBase
. Note though that a friend ofDerived
only has access to members inherited fromBase
to which Derived has access itself, e.g. ifDerived
inherits publicly fromBase
,Derived
only has access to the protected (and public) members inherited fromBase
, not the private members, so neither does a friend.