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:
struct Widget
{
operator Object() const;
};
Only the non-member version can be called if an instance of Widget
appears on the left-hand side:
Widget w;
Object o;
o + w; // can call Object::operator+( Object & ) since left-hand side is Object
w + o; // can only call operator+( Object &, Object & )
In response to your comment:
By defining the conversion operator in Widget
, we are notifying the compiler that instances of Widget
can be automatically converted to instances of Object
.
Widget w;
Object o = w; // conversion
In the expression o + w
, the compiler calls Object::operator+( Object & )
with an argument generated by converting w
to an Object
. So the result is the same as writing o + w.operator Object()
.
But in the expression w + o
, the compiler looks for Widget::operator+
(which doesn't exist) or a non-member operator+( Widget, Object )
. The latter can be called by converting w
to an Object
as above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With