hjjg200
hjjg200

Reputation: 345

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?

Upvotes: 9

Views: 196

Answers (2)

Naomi
Naomi

Reputation: 5486

Whenever your object is non-const there's a priority of non-constness over constness. The inner will be called when the left side is non-const, and the outer will be called when the left side is const.

See what happens when the inner is defined as:

string operator+( const A& rhs ) const;

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234715

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.

Upvotes: 4

Related Questions