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.