Where would you use a friend function vs. a static member function?

Swapna picture Swapna · Feb 23, 2010 · Viewed 24.8k times · Source

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())?

Answer

pm100 picture pm100 · Feb 23, 2010

Section 11.5 "The C++ Programming Language" by Bjarne Stroustrup states that ordinary member functions get 3 things:

  1. access to internals of class
  2. are in the scope of the class
  3. must be invoked on an instance

friends get only 1.

static functions get 1 and 2.