Operator overloading C++ reference or value

Johnnie W picture Johnnie W · Apr 28, 2016 · Viewed 8k times · Source

I've seen many tutorials and tried to find the answer on stackoverflow but with no success.

What I'm not sure of is; is there some praxis when to return by value or by reference, when overloading an operator?

For e.g.

Class &operator+(){
  Class obj;
  //...
  return obj;
}

or the same thing but by value

Class operator+(){
  Class obj;
  //...
  return obj;
}

And I'd like to mention, I've noticed that in almost 90% of cases when returning the same object (*this), is being referenced on the same object returned. Could someone explain why is that so, as well?

Answer

Niall picture Niall · Apr 28, 2016

... is there some praxis when to return by value or by reference, when overloading operator?

Yes, there are some canonical forms found here. They don't all have the same form - they vary by operator. The general advice is to follow the semantics of the built-in types. As with all functions, general rules still apply, such as not returning references to local variables (as shown in the OP).

E.g. (found in the link above) given the addition operator of the question;

class X
{
 public:
  X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
  {                           // but often is, to modify the private members)
    /* addition of rhs to *this takes place here */
    return *this; // return the result by reference
  }

  // friends defined inside class body are inline and are hidden from non-ADL lookup
  friend X operator+(X lhs,        // passing lhs by value helps optimize chained a+b+c
                     const X& rhs) // otherwise, both parameters may be const references
  {
    lhs += rhs; // reuse compound assignment
    return lhs; // return the result by value (uses move constructor)
  }
};

The operator+ is a non-member method (often as a friend) and returns by value - this corresponds to the semantics of the built in types. Similarly, the operator+= is a member method and returns by reference (an updated version of *this).

... when returning the same object (*this), is being referenced on the same object returned. Could someone explain why is that so, as well?

If the return type is by-value (X operator+), then return *this; means that a copy of the current object (what is pointed to by this) is made and returned.

If the return type is by-reference (X& operator+), then return *this; means that a reference to the current object (what is pointed to by this) is returned (i.e. not a copy).