0

When I can decide whether a particular function/operator should be declared as a friend function/operator for a class or a member function/operator of a class.?

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62

1 Answers1

1

Whenever you need to access the "guts" of your class (i.e. the private members) by a function that is not really related to your class. A typical example is the

friend std::ostream& operator<<(std::ostream& os, const Foo& foo)

which you overload so that you can simply display your object via the iostreams, like

std::cout << my_object;

In this case, assuming you need to grant access to your class private members, the function should be friend. It cannot even be a member function, since in that case you should call it like

my_object << (std::cout); 

which looks, well, quite odd.

vsoftco
  • 55,410
  • 12
  • 139
  • 252