friend is a keyword to grant private access to a function, member function or class.
Avoid unnecessary friendships [1]. Avoiding granting friendship to individual functions [2].
Example: overloading operator<<
In this example, operator<< is made a friend of class MyClass, so that operator<< can access the private variable mValue.
#include <iostream> struct MyClass { MyClass(const int value) : mValue(value) {} private: const int mValue; friend std::ostream& operator<<(std::ostream& os, const MyClass& myClass); }; std::ostream& operator<<(std::ostream& os, const MyClass& myClass) { os << "MyClass.value: " << myClass.mValue; return os; } int main() { const MyClass myClass(13); std::cout << myClass << '\n'; }
References
- John Lakos. Large-Scale C++ Software Design. 1996. ISBN: 0-201-63362-0. Chapter 9.1.13: 'Avoiding unnecessary friendships (even within the same component) can improve maintainability'
- John Lakos. Large-Scale C++ Software Design. 1996. ISBN: 0-201-63362-0. Chapter 9.1.13: 'Avoiding granting friendship to individual functions'