What are advantages/disadvantages of using friends in c++?

1 Like


  • using friends is generally syntactic. Ie: both a member fn and a friend are equally privileged
  • a friend function can be called like f(obj), where a member is called like obj.f().
  • friends are used when two or more classes are designed to be more tightly coupled than you want for.


  • they add to the global namespace. In contrast, the namespace of member functions is buried within the class, reducing the chance for namespace collisions for functions.
  • They aren’t inherited. That is, the `friendship privilege’ isn’t inherited. This is actually an advantage when it comes to encapsulation. Ex: I may declare you as my friend, but that doesn’t mean I trust your kids.
  • they don’t bind dynamically. Ie: they don’t respond to polymorphism. There are no virtual friends; if you need one, have a friend call a hidden (usually `protected:’) virtual member fn. Friends that take a ptr/ref to a class can also take a ptr/ref to a publicly derived class object, so they act as if they are inherited, but the friendship rights are not inherited