Given the following code snippet,
class Num
{
public:
Num(int iNumber = 0) : m_iNumber(iNumber) {}
Num operator+=(const Num& rhs)
{
Write the body like you did. Use the operator like you did. The operator should return a reference to allow chaining.
See here.
Returning by reference would be better
Num& operator+=(const Num& rhs){
this->m_iNumber += rhs.m_iNumber;
return *this;
}
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!
Your example is completely correct: http://codepad.org/PVhQw9sc .
int
does, it would need to return the type Num&
, and return the value *this
.If you follow to this Wikibook you'll find these answers by example:
Type& operator+=(const Type& right)
is the correct signature.Note as an added point (which you did right) the compound assignment operators have to be member functions.
Your operator function could also be written as
Num& operator += (const Num& rhs)
{
m_iNumber += rhs.m_iNumber;
return m_iNumber;
}
*this->m_iNumber
and m_iNumber
by itself within a member function are the same and using the former format is more typing in my opinion.