Search code examples
c++operatorscorrectness

Determining Plusequals Operator Syntax


I'm fairly new to c++ and am trying to learn about custom operators. The problem I'm having currently is in relation to defining my own += operator and the best way to go about it. This involves a simple class with a public int member (intValue) that can be added to. The following two code examples, which I've tried one at a time, operate exactly the same in my program as far as I can tell. By 'exactly the same' I mean I get the same result and create the same number of objects.

Which one is more correct (standard practice) and why?

Utility& operator +=(Utility& left, Utility right)
{
    return left = left + right;
}

Or

void operator +=(Utility& left, Utility right)
{
    left = left + right;
}

And, if it matters, the operator they call:

Utility operator +(Utility left, Utility right)
{
    return Utility(left.intValue + right.intValue);
}

The class prints out a message any time its constructor is called so I can tell if a new object is being made. Based on that the two forms of += I'm trying here result in the same number of objects being created.


Solution

  • Since += normally modifies its left-hand operand, you'd generally rather not implement it in terms of operator+ (which needs to create a temporary value to hold the result).

    Likewise, since you can't reasonably do a conversion on the left operand, it should really be a member function.

    Utility &Utility::operator+=(Utility const &right) { 
        intValue += right.intValue;
        return *this;
    }