1

I am trying to understand operator overloading of plus sign. I see 2 prototypes:

Box operator+(const Box& b) { ... }
Box operator+(const Box& left, const Box& right) { ... }

Which one is right? If the difference is only that first is member function and second is non-member, then lets say I define both ways, then which one will be called on ?

Box a, b;
Box c = a + b;
marcelovca90
  • 2,473
  • 2
  • 21
  • 32
BioLogic
  • 55
  • 5

1 Answers1

2

What is "right" or "better" depends on your application. The member version gives access to all private attributes and methods of Box, the non-member version doesn't unless it's declared as a friend of Box. But a non-member can be templated and made to apply to a wide range of types.

Members are not preferred by the compiler over non-members in general, nor vice versa. Instead C++ overload resolution rules are applied to select one or the other.

Box Box::operator+(const Box& b) is treated as though it takes two arguments: Box& which refers to the object used to call the member function (*this), and const Box& b.

In your example, both a and b are non-const.

In order to call Box Box::operator+(const Box& b), b needs to be converted to a const reference.

In order to call Box operator+(const Box& left, const Box& right), both a and b need to be converted to const references.

So the member operator is selected because it is a better match (requires less conversions).

Had your member operator+ been declared const, you would have gotten a compiler error because the call would become ambiguous.

rustyx
  • 62,971
  • 18
  • 151
  • 210
  • One other important difference: a non-member allows implicit conversions of the left hand operand to `Box`; a member does not. – aschepler May 15 '17 at 19:57