Skip to content

Chapter 14. Overloaded Operations and Conversions

Contents

In Chapter 4, we saw that C++ defines a large number of operators and automatic conversions among the built-in types. These facilities allow programmers to write a rich set of mixed-type expressions.

C++ lets us define what the operators mean when applied to objects of class type. It also lets us define conversions for class types. Class-type conversions are used like the built-in conversions to implicitly convert an object of one type to another type when needed.

Operator overloading lets us define the meaning of an operator when applied to operand(s) of a class type. Judicious use of operator overloading can make our programs easier to write and easier to read. As an example, because our original Sales_item class type (§ 1.5.1, p. 20) defined the input, output, and addition operators, we can print the sum of two Sales_items as

c++
cout << item1 + item2;  // print the sum of two Sales_items

In contrast, because our Sales_data class (§ 7.1, p. 254) does not yet have overloaded operators, code to print their sum is more verbose and, hence, less clear:

c++
print(cout, add(data1, data2));  // print the sum of two Sales_datas