Chapter 18

Overloading C++ Operators

WHAT’S IN THIS CHAPTER?

  • What operator overloading is
    • Rationale for overloading operators
    • Limitations, caveats, and choices in operator overloading
    • Summary of operators you can, cannot, and should not overload
  • How to overload unary plus, unary minus, increment, and decrement
  • How to overload the I/O streams operators (operator<< and operator>>)
  • How to overload the subscripting (array index) operator
  • How to overload the function call operator
  • How to overload the dereferencing operators (* and ->)
  • How to write conversion operators
  • How to overload the memory allocation and deallocation operators

C++ allows you to redefine the meanings of operators, such as +, -, and =, for your classes. Many object-oriented languages do not provide this capability, so you might be tempted to disregard its usefulness in C++. However, it can be beneficial for making your classes behave similarly to built-in types such as ints and doubles. It is even possible to write classes that look like arrays, functions, or pointers.

Chapters 3 and 4 introduce object-oriented design and operator overloading, respectively. Chapters 6 and 7 present the syntax details for objects and for basic operator overloading. This chapter picks up operator overloading where Chapter 7 left off.

This chapter focuses on the syntax and semantics of operator overloading. Practical examples are provided for most of the operators, but for a few of them, you already saw practical examples elsewhere ...

Get Professional C++, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.