C++ The friend Keyword
Lesson outline
Introduction to the friend Keyword
In C++, the friend keyword allows a non-member function, another class, or a specific member function of another class to access a class's private and protected members.
A friend is not a class member; it only gains access privileges. Declaring friendship is a way for a class to explicitly grant access to its internals.
Why Use the friend Keyword?
- Special Access Needs: Sometimes two entities must collaborate closely and need access to internal state.
- Operator Overloading: Common for symmetric non-member operators (e.g.,
operator<<) that require access to private data. - Coupled Types: When two types naturally need to inspect each other's internals in a controlled manner.
Friend Function Example
A friend function is not a member of the class but has access to its private and protected members.
Friend Class Example
When one class is declared as a friend of another, all member functions of the friend class can access the private and protected members of the granting class.
Friend Member Function Example (Correct Forward Declarations)
To befriend a specific member function, that function must be declared before the friendship is granted. Use forward declarations to make this work.
Friend and Operator Overloading
A common use of friend is to implement I/O operators that need access to private members while remaining non-members (to preserve symmetric conversions).
Important Notes
- Friendship is not inherited: a derived class does not gain friendship automatically.
- Friendship is not reciprocal: if A is a friend of B, B is not automatically a friend of A.
- Friendship is not transitive: if A befriends B and B befriends C, A is not a friend of C.
- Friendship is granted by the class being accessed, and it applies to the type, not to individual objects.
- Friend declarations can appear in any access section (public/private/protected); their placement does not change the level of access for other members.
Best Practices
- Use
friendsparingly and document why it is needed. - Prefer minimal exposure: friend a specific function instead of an entire class when possible.
- Consider alternative designs (public accessors, non-friend helper APIs) if they keep encapsulation intact without undue complexity.