11. Operator Overloading; String and Array Objects

Objectives

In this chapter you'll learn:

  • What operator overloading is and how it can make programs more readable and programming more convenient.

  • To redefine (overload) operators to work with objects of user-defined classes.

  • The differences between overloading unary and binary operators.

  • To convert objects from one class to another class.

  • When to, and when not to, overload operators.

  • To create PhoneNumber, Array, String and Date classes that demonstrate operator overloading.

  • To use overloaded operators and other member functions of standard library class string.

  • To use keyword explicit to prevent the compiler from using single-argument constructors to perform implicit conversions.

The whole difference between construction and creation is exactly this: that a thing constructed can only be loved after it is constructed; but a thing created is loved before it exists.

Gilbert Keith Chesterton

The die is cast.

Julius Caesar

Our doctor would never really operate unless it was necessary. He was just that way. If he didn't need the money, he wouldn't lay a hand on you.

Herb Shriner

Outline

11.1 Introduction
11.2 Fundamentals of Operator Overloading
11.3 Restrictions on Operator Overloading
11.4 Operator Functions as Class Members vs. Global Functions
11.5 Overloading Stream Insertion and Stream Extraction Operators
11.6 Overloading Unary Operators
11.7 Overloading Binary Operators
11.8 Case Study: Array Class
11.9 Converting between Types
11.10 Case Study: String Class
11.11 Overloading ++ and --
11.12 Case Study: A Date Class
11.13 Standard Library Class string
11.14 explicit Constructors
11.15 Wrap-Up