1

Suppose we have this class definition:

class A{
public:
    int a;
    A(int i): a(i){}
    A operator-() const { return A(- a); }     # first operator- function
};
A operator-(const A& o) { return A(- o.a); }   # second operator- function

Now, in the main function, if I write:

A a1(10);
A a2 = -a1;                # Here the first operator- function (method) is called!

However, if I remove the first definition of operator- in the class, the second function is called. I would llike to know why the compiler prefers the first definition when both of them are provided.

I would like to know also why the compiler accept to call the first function (method). Because I think that the method is synonym to a1- and not -a1 : The object on which the method is applied comes before (at the left of) the operator.

1

1 Answer 1

4

From the C++ standard, unary minus operator shall be defined like this:

T T::operator-() const;

inside class definition, and like this:

T operator-(const T &a);

outside class definition.

Now, you have both definition types in your class, so there member lookup comes in a play as specified here:

two separate lookups are performed: for the non-member operator overloads and for the member operator overloads (for the operators where both forms are permitted). Those sets are then merged with the built-in operator overloads on equal grounds as described in overload resolution. If explicit function call syntax is used, regular unqualified name lookup is performed

So, basically, member lookup finds A operator-() const;, non-member lookup finds A operator-(const A& o);. Overload resolution selects A operator-() const;.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.