Up to this point in the discussion of C++, the programmer could define operations on structure instance and class objects by using a function. For example:
c = add(a,b);
where a, b and c are instances of some structure or a class. However, this is using non-standard operators. C++ permits the programmer to use some of the standard operators in a more natural way using what is called: operator overloading. However, to do this requires that the programmer observe some restrictions.
To define operator overloading on class objects requires that the operator:
is a system operator.
maintains the system order of precedence
can not change type: i.e. between unary and binary operators
has at least one operand that is a class object.
is non static.
has in the operator's definition the keyword: operator
In addition, the programmer should take care how the operators are defined and that the operators should model their real world use. The permissible operators for overloading are:
OVERLOADABLE OPERATORS | ||||
---|---|---|---|---|
+ | - | * | / | % |
^ | & | | | ~ | ! |
, | = | < | > | <= |
>= | ++ | -- | _ | << |
>> | == | != | && | || |
+= | -= | /= | <<= | >>= |
[ ] | ( ) | -> | ->* | |
new | delete |
While most of the C++ operators can be overloaded, the dot operator (.) and some other operators can not be overloaded. The discussion in this lecture will only cover a few of the operators above.