C++ -- How to overload operator+=?

Given the following code snippet,

class Num
{
public:
    Num(int iNumber = 0) : m_iNumber(iNumber) {}

    Num operator+=(const Num& rhs)
    {
        this->m_iNumber = (this->m_iNumber + rhs.m_iNumber);
        return *this;
    }
private:
    int m_iNumber;
};

//===========================================================
int _tmain(int argc, _TCHAR* argv[])
{
    Num a(10);

    Num b(100);

    b += a;

    return 0;
}

I would like to know how to correctly overload the operator+=.

Questions:

  1. How to define the signature of this operator? Specially, what should be used for the return value?

  2. How to implement the function body?

  3. How to use this overload operator?

I have provided a solution as above but I have concerns that it is not correct.


Solution 1:

Returning by reference would be better

Num& operator+=(const Num& rhs){

      this->m_iNumber += rhs.m_iNumber;
      return *this;
}

Solution 2:

If you follow to this Wikibook you'll find these answers by example:

  1. Type& operator+=(const Type& right) is the correct signature.
  2. You did it right.
  3. You use an overloaded operator just like the plain operators, only with your type in place. That's kind of the point of the exercise. ;)

Note as an added point (which you did right) the compound assignment operators have to be member functions.

Solution 3:

The signature of any of the assignment operators (operator= or operator @= for your favorite operator @) should be

Class& operator @= (const Class& rhs);

That is, the function takes its parameter by const reference (because it doesn't modify it), then returns a mutable reference to the object. The reason you return a non-const reference is because, for historical reasons, you can write code like this:

(a += b) += c;

This is by no means good style, but it works for ints and so you should endeavor to make it work for your types as well.

As for the body of your function, what you have there is perfectly correct. In general, though, you should be sure that the code works even if the parameter is the receiver object. For example, if you write something like

a += a;

This gets translated into

a.operator+= (a);

And so the code will operate with both the parameter and the receiver being the same object. This usually doesn't come up for compound assignment operators (usually only operator= needs to worry about this), but in some cases you can get burned if you're not careful.

Finally, you can use this operator += function just as you have been in the example code above. Any use of += automatically calls it.

Hope this helps!

Solution 4:

Your example is completely correct: http://codepad.org/PVhQw9sc .

  1. You can define the return value to be whatever you want. If you wanted it to match what int does, it would need to return the type Num&, and return the value *this.
  2. You did it correctly.
  3. You also did that correctly.