Skip to main content

Chapter 20 Operator Overloads

Operator overloads allow us to define custom behavior for operators like + or == when applied to user-defined types.
Many programming languages do not support customizing operators to work with new data types. In those, we write and use functions like add(a, b) or a.equals(a) instead of using a + b or a == b when a and b are user-defined types.
C++ does allow us to overload operators to work on new data types. Sometimes, this ability is just a form of syntactic sugar (a syntax feature designed to make a particular language more pleasant to use). We can use operator overloading to enable writing the more natural a + b instead of a.add(b). However, it is sometimes necessary to define an operator overload not just for convenience, but to ensure that a fundamental operator like = (assignment) works correctly with user-defined types.
In this chapter, we will briefly explore how to define operator overloads. We will not cover all the possibilities and possible complications. Instead, we will focus on the basic principles and a few important operators. In future chapters we will rely on these ideas to build some new overloads.