Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ operator override - why is it friend preferred?

Tags:

c++

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?

like image 701
Johnny Pauling Avatar asked Oct 07 '12 00:10

Johnny Pauling


1 Answers

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.

like image 200
Andrew Durward Avatar answered Sep 19 '22 12:09

Andrew Durward