Which C++ operators can not be overloaded without friend function?

user366312 picture user366312 · Oct 24, 2011 · Viewed 7.7k times · Source

Which C++ operators can not be overloaded at all without friend function?

Answer

Michael Aaron Safyan picture Michael Aaron Safyan · Oct 24, 2011

You only need a friend declaration if:

  1. You define the operator as a standalone function outside the class, and
  2. The implementation needs to use private functions or variables.

Otherwise, you can implement any operator without a friend declaration. To make this a little bit more concrete... one can define various operators both inside and outside of a class*:

 // Implementing operator+ inside a class:
 class T {
   public:
    // ...
    T operator+(const T& other) const { return add(other); }
    // ...
 };

 // Implementing operator+ outside a class:
 class T {
   // ...
 };

 T operator+(const T& a, const T& b) { return a.add(b); }

If, in the example above, the "add" function were private, then there would need to be a friend declaration in the latter example in order for operator+ to use it. However, if "add" is public, then there is no need to use "friend" in that example. Friend is only used when granting access is needed.

*There are cases where an operator cannot be defined inside a class (e.g. if you don't have control over the code of that class, but would still like to provide a definition where that type is on the left-hand side, anyway). In those cases, the same statement regarding friend declarations still holds true: a friend declaration is only needed for access purposes. As long as the implementation of the operator function relies only on public functions and variables, a friend declaration is not needed.