Reputation: 161
I want to overload two operators: += and +
what is basically the difference between them? is += just modifying the current object and + returns a new object?
Upvotes: 1
Views: 473
Reputation: 2151
It's just like you said, operator+= works in-place (it modifies the current object), while operator+ returns a new object and leaves its parameters unchanged.
A common way to implement them for a type T
is as follows:
// operator+= is a member function of T
T& T::operator+=(const T& rhs)
{
// perform the addition
return *this;
}
// operator+ is a free function...
T operator+(T lhs, const T& rhs)
{
// ...implemented in terms of operator+=
lhs += rhs;
return lhs;
}
Upvotes: 4