The code is implemented within one .cpp file:

class Foo { public: int m_a; Foo(int num) : m_a(num){} Foo operator+(const Foo& f); { return m_a + f1.m_a; } }; Foo operator+(const Foo& f1, const Foo& f2) { return f1.m_a + f2.m_a; } 

Why is operator overloading caused by a method and there is no call uncertainty

  • the code is not correct, the second operator should be a free function - Abyx
  • Clean ; after Foo operator+(const Foo& f); . And what is f1 inside a class method? - AnT
  • "Why the operator is overloaded via the method ..." - this is incorrect. What kind of overload will be caused - depends on the parameters. - AnT

1 answer 1

Uncertainty of the call does not occur because the overload through the method is not declared as const . As a result, your overload through the method implements the overload of the binary operator + for parameters

 не-const + const 

And the overload by a separate function implements the overload of the binary operator + for parameters

 const + const 

This difference in the constancy of the first argument allows the compiler to avoid ambiguity when choosing a method. for example

 int main() { Foo a(0), b(0); a + b; // Вызывается перегрузка методом класса const Foo ca(0), cb(0); ca + cb; // Вызывается перегрузка отдельной функцией } 

If you add const your method declaration

 Foo operator+(const Foo& f) const { return m_a + f.m_a; } 

then both overloads will immediately become fully equivalent and the compiler will start to swear at ambiguity when trying to use the operator.