C++ allows the function of most built-in operators to be redefined. These operators can be redefined, or “overloaded,” globally or on a class-by-class basis. Overloaded operators are implemented as functions, and can be class-member or global functions.
The name of an overloaded operator is operatorx, where x is the operator as it appears in Table 12.2. For example, to overload the addition operator, you define a function called operator+. Similarly, to overload the addition/assignment operator, +=, define a function called operator+=.
While these operators are usually called implicitly by the compiler when they are encountered in code, they can be invoked explicitly the same way as any member or nonmember function is called:
Point pt;
pt.operator+( 3 ); // Call addition operator to add 3 to pt.
Table 12.2 shows a list of operators that can be overloaded.
Table 12.2 Redefinable Operators
Operator | Name | Type |
, | Comma | Binary |
! | Logical negation | Unary |
!= | Inequality | Binary |
% | Modulus | Binary |
%= | Modulus/assignment | Binary |
& | Bitwise AND | Binary |
& | Address-of | Unary |
&& | Logical AND | Binary |
&= | Bitwise AND/assignment | Binary |
() | Function call | —- |
* | Multiplication | Binary |
* | Pointer dereference | Unary |
*= | Multiplication/assignment | Binary |
+ | Addition | Binary |
+ | Unary Plus | Unary |
++ | Increment1 | Unary |
+= | Addition/assignment | Binary |
– | Subtraction | Binary |
– | Unary negation | Unary |
–– | Decrement1 | Unary |
–= | Subtraction/assignment | Binary |
–> | Member selection | Binary |
–>* | Pointer-to-member selection | Binary |
/ | Division | Binary |
/= | Division/assignment | Binary |
< | Less than | Binary |
<< | Left shift | Binary |
<<= | Left shift/assignment | Binary |
Table 12.2 (continued)
Operator | Name | Type |
<= | Less than or equal to | Binary |
= | Assignment | Binary |
== | Equality | Binary |
> | Greater than | Binary |
>= | Greater than or equal to | Binary |
>> | Right shift | Binary |
>>= | Right shift/assignment | Binary |
[] | Array subscript | —- |
Exclusive OR | Binary | |
^= | Exclusive OR/assignment | Binary |
| | Bitwise inclusive OR | Binary |
|= | Bitwise inclusive OR/assignment | Binary |
|| | Logical OR | Binary |
~ | One's complement | Unary |
delete | delete | —- |
new | new | —- |
1Two versions of the unary increment and decrement operators exist: preincrement and postincrement.
The constraints on the various categories of overloaded operators are described in “Unary Operators”, “Binary Operators”, “Assignment”, “Function Call”, “Subscripting”, “Class Member Access” on page 363, and “Increment and Decrement”.
The operators shown in Table 12.3 cannot be overloaded.
Table 12.3 Nonredefinable Operators
Operator | Name |
. | Member selection |
.* | Pointer-to-member selection |
:: | Scope resolution |
:> | Base operator |
? : | Conditional |
# | Preprocessor symbol |
## | Preprocessor symbol |