hʌn hʌn - 1 month ago 8
C++ Question

How does an operator inside a class work?

class A {
public:
string operator+( const A& rhs ) {
return "this and A&";
}
};

string operator+( const A& lhs, const A& rhs ) {
return "A& and A&";
}

string operator-( const A& lhs, const A& rhs ) {
return "A& and A&";
}

int main() {
A a;
cout << "a+a = " << a + a << endl;
cout << "a-a = " << a - a << endl;
return 0;
}

//output
a+a = this and A&
a-a = A& and A&


I'm curious as to why the operator inside the class gets to be called rather than the outside one. Is there some sort of priority among operators?

Answer

The process of selecting amongst several functions of the same name is called overload resolution. In this code, the member is preferred because the non-member requires a qualification conversion (adding const to lhs) but the member does not. If you made the member function const (which you should, since it does not modify *this) then it would be ambiguous.