uchar
uchar

Reputation: 2590

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

  //....
}

Upvotes: 4

Views: 254

Answers (2)

Manu343726
Manu343726

Reputation: 14174

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

Upvotes: 6

user2249683
user2249683

Reputation:

Yes you can do it your way:

BigNumber& operator +=(const BigNumber& other)
{
    *this=(*this) + other;
    return *this;
}

The usual approach is the opposite way:

// Note a is no const reference
BigNumber operator + (BigNumber a, const BigNumber& b)
{
    return a += b;
}

A reasoning for your approach might be memory allocation.

Upvotes: 1

Related Questions