Compound-Assignment Operators

Compound assignment operators are not required to be members. However, we prefer to define all assignments, including compound assignments, in the class. For consistency with the built-in compound assignment, these operators should return a reference to their left-hand operand. For example, here is the definition of the Sales_data compound-assignment operator:

// member binary operator: left-hand operand is bound to the implicit this pointer// assumes that both objects refer to the same bookSales_data& Sales_data::operator+=(const Sales_data &rhs){    units_sold += rhs.units_sold;    revenue += rhs.revenue;    return *this;}

Best Practices

Assignment operators must, and ordinarily compound-assignment operators ...

Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.