We make a non-member function a friend of a class when we want it to access that class's private members. This gives it the same access rights as a static member function would have. Both alternatives would give you a function that is not associated with any instance of that class.
When must we use a friend function? When must we use a static function? If both are viable options to solve a problem, how do we weigh up their suitability? Is there one that should be preferred by default?
For example, when implementing a factory that creates instances of class foo
which only has a private constructor, should that factory function be a static member of foo
(you would call foo::create()
) or should it be a friend function (you would call create_foo()
)?
Section 11.5 "The C++ Programming Language" by Bjarne Stroustrup states that ordinary member functions get 3 things:
friend
s get only 1.
static
functions get 1 and 2.