Arithmetic operators

suggest change

You can overload all basic arithmetic operators:

Overloading for all operators is the same. Scroll down for explanation

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)
{
    *this += rhs;
    return *this;
}

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 the itself, because it is then possible to chain them (don’t use the same variable though, that would be undefined behavior due to sequence points).

The first argument is a reference (we want to modify it), but not const, because then you wouldn’t be able to modify it. The second argument should not be modified, and so for performance reason is passed by const& (passing by const reference is faster than by value).

Feedback about page:

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


Operator overloading:
* Arithmetic operators

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
55 Operator overloading
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype