As you prepare to overload operators for your own classes, there are several rules and restrictions you should keep in mind:
• The precedence of an operator cannot be changed by overloading. However, parentheses can be used to force the order of evaluation of overloaded operators in an expression.
• The associativity of an operator cannot be changed by overloading—if an operator normally associates from left to right, then so do all of its overloaded versions.
• You cannot change the “arity” of an operator (that is, the number of operands an operator takes)—overloaded unary operators remain unary operators; overloaded binary operators remain binary operators. Operators &
, *
, +
and -
all have both unary and binary versions; these unary and binary versions can be separately overloaded.
• You cannot create new operators; only existing operators can be overloaded.
• The meaning of how an operator works on values of fundamental types cannot be changed by operator overloading. For example, you cannot make the +
operator subtract two int
s. Operator overloading works only with objects of user-defined types or with a mixture of an object of a user-defined type and an object of a fundamental type.
• Related operators, like + and +=, must be overloaded separately.
• When overloading ()
, []
, ->
or any of the assignment operators, the operator overloading function must be declared as a class member. For all other overloadable operators, the operator overloading functions can be member functions or non-member functions.
Software Engineering Observation 10.1
Overload operators for class types so they work as closely as possible to the way built-in operators work on fundamental types.