How to read Chapter 11
Chapter 11 is about operator overloading. Operator overloading
is especially useful for "numeric" classes, such as Rational and
Complex. It's much nicer to be able to use the various
arithmetic and relational operators than to have to write out
member function calls. However, defining such operators can get
tricky, particularly for the prefix and postfix increment and
For most other user-defined classes, the main operators you
need to overload are operator<< and possibly
operator>> (Section 11.5),
and the assignment operator (page 592).
A few points about operator overloading I want to emphasize:
- Unless there's a performance bottleneck, do not make
operators friend's of the class. Implement
operators with public member functions.
- You must declare overloaded operators in the header file of the
class, whether they're friend's or not.
- In the assignment operator, make sure to check for and
do nothing when self assignment occurs. Self assignment
can happen more often than you think. Check for self assignment
with if (this == &value) ... where value
is the value being stored.
- Define the assignment operator to return a reference to
*this, so that r1 = r2 = ... will work
correctly. This is shown on lines 52-70 of Figure 11.7.
Note that some respected texts, such as
Scott Meyers' Effective C++,
say that you should return a simple reference,
not a const reference.
- For other binary operators, use the two-argument non-member function
rather than the one-argument member function, e.g.,
use operator+(const &Type, const &Type).
- Note that the syntax is a bit obscure for overloading
the prefix and postfix increment and decrement operators. See
page 608 for details.