Arithmetic operators
suggest changeYou can overload the basic arithmetic operators. The same pattern also covers the bitwise operators:
+and+=-and-=*and*=/and/=&and&=|and|=^and^=>>and>>=<<and<<=
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
- You can’t modify the original object (
Object foobar = foo + bar;shouldn’t modifyfooafter all, it wouldn’t make sense) - You can’t make it
const, because you will have to be able to modify the object (becauseoperator+is implemented in terms ofoperator+=, 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.