Introduction
Chapters 910 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 objectsa 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 22, 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. [Note: The bitwise left-shift and bitwise right-shift operators are discussed in detail in Chapter 22.] 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 the programmer to overload most operators to be sensitive to the context in which they are usedthe compiler generates the appropriate code based on the context (in particular, the types of the operands). Some operators are overloaded frequently, especially the assignment operator 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. In the exercises, we ask you to implement several classes with overloaded operators. The exercises also use classes Complex (for complex numbers) and HugeInt (for integers larger than a computer can represent with type long) to demonstrate overloaded arithmetic operators + and - and ask you to enhance those classes by overloading other arithmetic operators.