The friend keyword allows a specific function or another class to access the private and protected members of the class where friend is declared. Friend functions can be either global or methods of other classes. This construct enables the implementation of functions that require access to the internal state of the class but are logically not related to the interface of that class.
It is recommended to use friend:
Caution:
Example:
class Box { int width; public: Box(int w): width(w) {} friend void printWidth(const Box &b); }; void printWidth(const Box &b) { std::cout << b.width << std::endl; }
Question: Can a friend function be virtual?
Common Answer: Yes, since friend is a function modifier.
Correct Answer: No, friend functions cannot be virtual because they are not members of the class!
Example:
class Example { friend virtual void foo(); // Compilation error: virtual does not apply to friend };
Story: While designing a matrix library, all arithmetic operators were made friend functions for speed, but they forgot about supporting const-correctness and excessively opened access to private members. Later a problem arose — in the project other functions inadvertently altered the internal state of Matrix.
Story: In a corporate system, helper classes became friends with each other to share access to private members. This led to cyclic dependencies — adding a new feature required changing all related classes. The subsequent refactoring took weeks.
Story: For closed tests, it was decided to make the test class a friend to the production class. When several sets of unit tests appeared, it became impossible to track which private methods were actually used — tests began to depend on the internal implementation, leading to complicated code maintenance.