Is it right to define operator += in this way ?!
void operator +=(const BigNumber& other)
{
*this=(*this) + other;
}
In a class like this :
class BigNumber
{
public:
//....
BigNumber operator +(const BigNumber& other)
{
return sum(other);
}
//....
}
Yes. But the right way is to implement operator+
in terms of operator+=
:
struct foo
{
int value;
foo& operator+=( const foo& other )
{
value += foo.value;
return *this ;
}
friend foo operator+( foo lhs , const foo& rhs )
{
return lhs += rhs;
}
};
First of all, the binary operator+()
shouldn't be defined as member function instead of free function. This allows you to implement addition where the first parameter is not a foo
. The common idiom is to declare it friend
inside the class to ride over encapsulation.
Second, this way provides a coherent, maintainible, and efficient interface.
If you implement a +=
operation, the user spects (Except in rare cases) the type provides a binary addition too. Implementing +
with +=
provides this ensuring that the behavior of the two operations is coherent.
You have implemented +
using +=
, so the code which really performs the addition is written only once. If you need to change the operation in the future you have to change one code only, and if it has a bug that bug is in one site only. Reducing code duplication is a good practice in general.
The way the operator+()
is written allows the compiler to easily elide copies, boosting the performance of the binary addition.
The idiom used is "copy first operand, operate on it, return the copy". So the compiler can easily perform a return value optimization (RVO). Also, it passes the first operand by value instead of copying the operand by hand inside the function. This allows the compiler to perform more copy elisions when the first operand is an rvalue (Let the compiler decide when and how to copy).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With