11.3. Restrictions on Operator Overloading
Common Programming Error 11.1
Precedence, Associativity and Number of Operands
The precedence of an operator cannot be changed by overloading. This can lead to awkward situations in which an operator is overloaded in a manner for which its fixed precedence is inappropriate. However, parentheses can be used to force the order of evaluation of overloaded operators in an expression.
It is not possible to change the "arity" of an operator (i.e., the number of operands an operator takes): Overloaded unary operators remain unary operators; overloaded binary operators remain binary operators. C++'s only ternary operator (?:) cannot be overloaded. Operators &, *, + and - all have both unary and binary versions; these unary and binary versions can each be overloaded.
Common Programming Error 11.2
Creating New Operators
It is not possible to create new operators; only existing operators can be overloaded. Unfortunately, this prevents the programmer from using popular notations like the ** operator used in some other programming languages for exponentiation. [Note: You could overload the ^ operator to perform exponentiationas it does in some other languages.]
Common Programming Error 11.3
Operators for Fundamental Types
The meaning of how an operator works on objects of fundamental types cannot be changed by operator overloading. The programmer cannot, for example, change the meaning of how + adds two integers. 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.
Software Engineering Observation 11.2
Common Programming Error 11.4
Overloading an assignment operator and an addition operator to allow statements like
object2 = object2 + object1;
object2 += object1;
Such behavior can be achieved only by explicitly overloading operator += for that class.
Common Programming Error 11.5