ThunderPhoenix
ThunderPhoenix

Reputation: 1883

How to define correctly unary operator- in C++

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.

Upvotes: 0

Views: 1233

Answers (1)

NutCracker
NutCracker

Reputation: 12273

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;.

Upvotes: 3

Related Questions