Assignment operators should behave analogously to the synthesized operators: After an assignment, the values in the left-hand and right-hand operands should have the same value, and the operator should return a reference to its left-hand operand. Overloaded assignment should generalize the built-in meaning of assignment, not circumvent it.
Caution: Use Operator Overloading Judiciously
Each operator has an associated meaning from its use on the built-in types. Binary +
, for example, is strongly identified with addition. Mapping binary +
to an analogous operation for a class type can provide a convenient notational shorthand. For example, the library string
type, following a convention common to many programming languages, uses +
to represent concatenation—“adding” one string
to the other.
Operator overloading is most useful when there is a logical mapping of a built-in operator to an operation on our type. Using overloaded operators rather than inventing named operations can make our programs more natural and intuitive. Overuse or outright abuse of operator overloading can make our classes incomprehensible.
Obvious abuses of operator overloading rarely happen in practice. As an example, no responsible programmer would define operator+
to perform subtraction. More common, but still inadvisable, are uses that contort an operator’s “normal” meaning to force a fit to a given type. Operators should be used only for operations that are likely to be unambiguous to users. An operator has an ambiguous meaning if it plausibly has more than one interpretation.
If a class has an arithmetic (§ 4.2, p. 139) or bitwise (§ 4.8, p. 152) operator, then it is usually a good idea to provide the corresponding compound-assignment operator as well. Needless to say, the +=
operator should be defined to behave the same way the built-in operators do: it should behave as +
followed by =
.