C++ Operator Overloading
To use and operator on class objects, the operator must be overloaded for the class -
with tow exceptions:
- The assignment operator ( = ) may be used with every class without explicit overloading.
The default begivior of this operator is to make a memberwise copy of the data members
of the class. This is dangerous for classes with members which point to dynamically allocated
storage.
- The address of operator ( & ) may be used without overloading since it simply returns
the address in memory of the object. Pretty unambiguous.
C++ is an operator rich language. The following operators can be overloaded:
| + | - | * | / | % | ^ | & | | | ~ | ! | = |
| < | > | += | -= | *= | /= | %= | ^= | &= | |= | << |
| >> | >>= | <<= | == | != | <= | >= | && | || | ++ | -- |
| ->* | , | -< | [] | () | new | delete |
The following operators cannot be overloaded:
The following general rules apply when overloading an operator in C++:
- You cannot change operator precedence by overloading.
- You cannot create new operators. You can overload only existing operators.
- You cannot change the meaning of how an operator works on objects of built-in types by overloading.