Overloading Summary
We now have three ways to overload (some) operators
- As a member function (required for some operators)
- As a non-member function
- As a (non-member) friend function
but some restrictions apply and some guidelines dictate
which way is best (but not always).
Restrictions
- Not all operators can be overloaded.
- You can't make up your own operators.
- You can't overload operators for primitive types.
- You can't change the precedence of an operator.
- You can't change the associativity of an operator.
Good Programming Practice
- Overload operators so that they mimic the behavior of primitive data types.
- Overloaded binary arithmetic operators should
- return const objects by value
- be written as non-member functions when appropriate to allow commutativity
- be written as non-friend functions (if data member accessors are available)
- Overload unary operators as member functions.
- Always overload<<
- Overload operator= if your class uses dynamic memory allocation
Exercises for the student
Using the code for the Money class from the text, write the prototypes
and implementations for other overloaded operators. Be sure to try
comparison operators like <, >, !=, etc. and arithemtic operators
like += and -=. Also try some unary operators such as ++ and --.
Last Modified: Monday, 28-Aug-2006 10:15:53 EDT