Friends in C++
Let’s start by reviewing the way in which C++ grants friendship to classes, and the effects of this action, as well as when and for what reasons the friendship should be used (“my code does not compile until I add friend
everywhere” is not a valid reason, but an indication of a poorly designed interface - redesign your classes instead).
How to grant friendship in C++
A friend is a C++ concept that applies to classes and affects the access to class members (access is what public
and private
control). Usually, public member functions and data members are accessible to anyone, and private ones are only accessible to other member functions of the class itself. The following code does not compile because the data member C:x_
is private:
// Example 01 class C { int x_; public: C(int x) : x_(x) {} }; C increase(C c, int dx) { return C(c.x_ + dx); // Does not compile }...