11.1. Introduction
Chapters
9–10 introduced the basics of C++ classes. Services were obtained
from objects by sending messages (in the form of member-function calls) to the
objects. This function call notation is cumbersome for certain kinds of classes
(such as mathematical classes). Also, many common manipulations are performed
with operators (e.g., input and output). We can use C++'s rich set of built-in
operators to specify common object manipulations. This chapter shows how to
enable C++'s operators to work with objects—a process called operator overloading. It is
straightforward and natural to extend C++ with these new capabilities, but it
must be done cautiously.
One example of an overloaded operator
built into C++ is <<, which is used both as
the stream insertion operator and as the bitwise left-shift operator (which is
discussed in Chapter
19, Bits, Characters, Strings and structs). Similarly,
>> is also overloaded; it is used both
as the stream extraction operator and as the bitwise right-shift operator. Both
of these operators are overloaded in the C++ Standard Library.
Although operator overloading
sounds like an exotic capability, most programmers implicitly use overloaded
operators regularly. For example, the C++ language itself overloads the addition
operator (+) and the subtraction operator
(-). These operators perform differently,
depending on their context in integer arithmetic, floating-point arithmetic and
pointer arithmetic.
C++ enables you to overload most
operators to be sensitive to the context in which they are used—the compiler
generates the appropriate code based on the context (in particular, the types of
the operands). Some operators are overloaded frequently, especially the
assignment, relational and various arithmetic operators such as + and
-. The jobs performed by overloaded
operators can also be performed by explicit function calls, but operator
notation is often clearer and more familiar to programmers.
We discuss when to, and when not to, use
operator overloading. We implement user-defined classes PhoneNumber,
Array, String and Date
to demonstrate how to overload operators, including the stream insertion, stream
extraction, assignment, equality, relational, subscript, logical negation,
parentheses and increment operators. The chapter ends with an example of C++'s
Standard Library class string, which
provides many overloaded operators that are similar to our String class
that we present earlier in the chapter.