Continuing from the previous question I’d like to ask why the “friend” form of addition in a C++ operator override is preferred
To summarize:
for the addition operator override there are two ways to do it:
int operator+(Object& e);
friend int operator+(Object& left, Object& right);
why is that the second (friend) form is preferred? What are the advantages?
The non-member version (friend or otherwise) is preferred because it can support implicit conversions on both the left and right side of the operator.
Given a type that is implicitly convertible to Object:
Only the non-member version can be called if an instance of
Widgetappears on the left-hand side:In response to your comment:
By defining the conversion operator in
Widget, we are notifying the compiler that instances ofWidgetcan be automatically converted to instances ofObject.In the expression
o + w, the compiler callsObject::operator+( Object & )with an argument generated by convertingwto anObject. So the result is the same as writingo + w.operator Object().But in the expression
w + o, the compiler looks forWidget::operator+(which doesn’t exist) or a non-memberoperator+( Widget, Object ). The latter can be called by convertingwto anObjectas above.