Why is it more efficient to set the + operator to call the + = operator rather than the reverse?

advertisements

It's an exercise from C++ Primer 5th Edition:

Exercise 14.14: Why do you think it is more efficient to define operator+ to call operator+= rather than the other way around?(P.561)

Given the implementations for operator+= and operator+:

Sales_data&
Sales_data::operator+=(const Sales_data &rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}

Sales_data
operator+(const Sales_data &lhs, const Sales_data &rhs)
{
    Sales_data sum = lhs;  // copy data members from lhs into sum
    sum += rhs;             // add rhs into sum
    return sum;
}

At the end of this section (14.3) , the author gave a tip that

Classes that define both an arithmetic operator and the related compound assignment ordinarily ought to implement the arithmetic operator by using the compound assignment.

Can anyone explain this tip, using facts/examples?


operator+= would use an unnecessary temporary object if it were implemented using operator+, as you can see in the first line of the operator+ example.