Chapter 14. Overloaded Operations and Conversions
Contents
- Section 14.1 Basic Concepts
- Section 14.2 Input and Output Operators
- Section 14.3 Arithmetic and Relational Operators
- Section 14.4 Assignment Operators
- Section 14.5 Subscript Operator
- Section 14.6 Increment and Decrement Operators
- Section 14.7 Member Access Operators
- Section 14.8 Function-Call Operator
- Section 14.9 Overloading, Conversions, and Operators
- Chapter Summary
- Defined Terms
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_item
s as
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:
print(cout, add(data1, data2)); // print the sum of two Sales_datas