Arithmetic operators

suggest change

You can overload the basic arithmetic operators. The same pattern also covers the bitwise operators:

The same general pattern applies to each pair of operators.

Overloading outside of class/struct:

//operator+ should be implemented in terms of operator+=
T operator+(T lhs, const T& rhs)
{
    lhs += rhs;
    return lhs;
}

T& operator+=(T& lhs, const T& rhs)
{
    //Perform addition
    return lhs;
}

Overloading inside of class/struct:

// operator+ should be implemented in terms of operator+=
T operator+(const T& rhs) const
{
    T result(*this);
    result += rhs;
    return result;
}

T& operator+=(const T& rhs)
{
    //Perform addition
    return *this;
}

Note: operator+ should return by non-const value, as returning a reference wouldn’t make sense (it returns a new object) nor would returning a const value (you should generally not return by const). The first argument is passed by value, why? Because

  1. You can’t modify the original object (Object foobar = foo + bar; shouldn’t modify foo after all, it wouldn’t make sense)
  2. You can’t make it const, because you will have to be able to modify the object (because operator+ is implemented in terms of operator+=, which modifies the object)

Passing by const& would be an option, but then you will have to make a temporary copy of the passed object. By passing by value, the compiler does it for you.


operator+= returns a reference to its left operand, which permits chaining such as a += b += c. Evaluation-order rules still matter in more complicated expressions, especially when the same object is modified more than once.

The first argument is a non-const reference because the operator modifies it. Passing the second argument by const& avoids a copy for larger types, although passing small, inexpensive types by value may be preferable.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents