Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call operator + in operator +=

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);
    }

  //....
}
like image 663
uchar Avatar asked Mar 20 '23 22:03

uchar


1 Answers

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;
    }
};

Why?

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.

Coherency:

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.

Maintainability:

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.

Efficiency:

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).

like image 53
Manu343726 Avatar answered Apr 19 '23 13:04

Manu343726