skip to content

In C++, what are the canonical signatures of operator+= and operator+ for a Money type, and why is + written using +=?

level: middleimportance: must knowfreq 60%

answer

  1. one modifies, one creates
  2. return *this by reference
  3. new value, returned by value
  4. left operand taken by value

basics

~10 s

operator+= is a member that modifies the object and returns Money& (*this); operator+ is usually a non-member that returns a new Money by value. Writing + as copy-then-+= keeps the arithmetic in one place.

solid answer

~50 s

The two operators mirror the built-in ones. `a += b` changes `a` and yields `a` itself, so the canonical form is a **member** `Money& operator+=(const Money& rhs)` that updates the members and ends with `return *this;`, which lets `(a += b) += c` chain like it does for `int`. `a + b` changes neither operand and yields a new value, so it returns **`Money` by value**: returning a reference would refer to a local that is gone, and returning `const Money` blocks moving from the result. The usual body is `Money operator+(Money lhs, const Money& rhs) { lhs += rhs; return lhs; }`. Taking `lhs` **by value** makes the copy it needs anyway, lets a temporary such as the result of `a + b` initialize it directly instead of being copied, and keeps all the arithmetic (overflow checks, currency checks) inside `+=`.

code

cpp · 24 lines
cpp
#include <cstdio>

class Money {
    long long cents_ = 0;
public:
    explicit Money(long long cents) : cents_(cents) {}
    long long cents() const { return cents_; }

    Money& operator+=(const Money& rhs) {   // member: it modifies *this
        cents_ += rhs.cents_;
        return *this;                       // reference, so (a += b) += c chains
    }
    friend Money operator+(Money lhs, const Money& rhs) {
        lhs += rhs;                         // one place holds the arithmetic
        return lhs;                         // by value; a parameter is moved, not elided
    }
};

int main() {
    Money a(1000), b(250), c(5);
    Money total = a + b + c;   // the prvalue a + b initializes lhs directly
    (a += b) += c;
    std::printf("%lld %lld\n", total.cents(), a.cents());   // 1255 1255
}

go deeper

for a junior

Recall that += returns Money& and ends with return *this, while + returns a new Money by value.

for a middle

Explain why + is written via +=, why its left operand is taken by value, and why returning a reference or a const value from + is wrong.

for a senior

Show how to choose the operator set from the domain, which operations exist at all, and where checks such as overflow or currency mismatch belong.

for a principal

Set the value-type conventions a codebase follows, such as hidden-friend binary operators and compound forms as members, so reviews do not relitigate each type.

## The rule behind the canonical forms An overloaded operator should behave like the built-in operator with the same spelling, because readers bring their expectations about `int` with them. Two observations about `int` fix the shapes: - `a += b` **modifies `a`** and the expression **is** `a` (an lvalue). You can write `(a += b) += c`. - `a + b` **modifies neither operand** and the expression is a **new value** (a prvalue). ## operator+=: a member returning a reference ```cpp Money& operator+=(const Money& rhs) { cents_ += rhs.cents_; return *this; } ``` - It is a **member**, because it changes the object's private state and its left operand must already be a `Money`; nothing should be converted into a temporary just to be modified and thrown away. - It returns **`Money&`**, the object itself, so chaining works and no copy is made. - The right operand is `const Money&`: it is only read. ## operator+: a non-member returning a value ```cpp friend Money operator+(Money lhs, const Money& rhs) { lhs += rhs; return lhs; } ``` Each choice has a reason: 1. **Return by value.** The result is a new object. Returning `Money&` or `Money&&` to a local would leave the caller with a dangling reference, and using it is undefined behaviour. 2. **Do not return `const Money`.** Older advice used a `const` return to reject `(a + b) = c`. Since C++11 that also prevents moving from the result, so it costs performance for no real safety. 3. **Take the left operand by value.** The function needs a copy to modify anyway. When the caller passes a temporary, as in `a + b + c`, where `a + b` is a prvalue, that temporary initializes `lhs` directly instead of being copied. 4. **Implement `+` with `+=`.** The arithmetic, including any overflow or currency check, lives in one function, so the two operators cannot drift apart. 5. **Make it a non-member**, often a *hidden friend* defined inside the class, so that the left operand is not forced to be a `Money` already; symmetry between operand orders is the reason, and the rules for finding hidden friends belong to the material on namespaces and lookup. ## The wider family of canonical forms The same reasoning gives the rest of the arithmetic and comparison set: | Operator | Usual form | Returns | |---|---|---| | `+=`, `-=`, `*=` | member | `Money&` (`*this`) | | `+`, `-`, `*` | non-member, via the compound form | `Money` by value | | unary `-` | member or non-member | `Money` by value | | prefix `++` | member | `Money&` | | postfix `++` | member with a dummy `int` parameter | the old value, by value | | `==` | member or non-member, or `= default` in C++20 | `bool` | | `<=>` | `= default` or by hand, C++20 | a comparison category | ## What to say about domain rules For money specifically, the canonical *shape* does not decide the *set*. `Money + Money` makes sense; `Money * Money` does not, so it should simply not exist, and `Money * long long` scales an amount. Mixed currencies are a domain decision: `+=` is the one place to check them, which is another reason to route `+` through it. Choosing these signatures well is what interviewers are really testing: whether you can tell an operator that matches the built-in shape from one that merely compiles. ## Mistakes that reviews keep finding 1. **Returning a reference to a `static` local** to "avoid the copy". Every call shares one object, so `(a + b) == (c + d)` compares that object with itself and is always true. A run with 1 + 2 and 30 + 40 prints `1`. 2. **Implementing `+=` in terms of `+`** (`*this = *this + rhs;`). It works, but it builds a temporary for every compound assignment, the opposite of the efficient direction. 3. **Taking `rhs` by value** as well. Only `lhs` benefits, because only `lhs` is modified and returned. 4. **Forgetting `const`** on read-only operands, which stops `const Money` objects and temporaries from being added. ## Checking the forms in code The code example builds `a + b + c` and `(a += b) += c` and prints the same total for both, which is a quick way to confirm that the two operators agree.

  • Why does operator+= not return void?
    Returning `void` would compile, but `(a += b) += c` and `f(a += b)` would stop working, and the operator would no longer behave like the built-in one. Returning `*this` by reference costs nothing and keeps the expected semantics.
  • Why not take both operands of operator+ by const reference?
    It works, but the body must then copy `lhs` itself, and that copy is made even when the caller passed a temporary. Taking `lhs` by value lets a prvalue such as `a + b` initialize the parameter directly, saving a copy in chained expressions.

  • operator+ should return a reference to avoid copying the result
  • operator+= should return a new Money by value
  • Returning const Money from operator+ is free extra safety
  • operator+ and operator+= should each implement the arithmetic separately
  • Every arithmetic operator must be a member function