Chapter 5 described how you can redefine the meaning of the assignment operator (=) when used to assign objects of a class you write. That was an example of operator overloading, and the assignment operator is the operator most commonly overloaded when writing classes.
You can overload other operators to make your code more readable. For example, suppose you needed a function that compares Date objects, to see if one comes before another. You can write a function called lessThan and use it as follows:
if( lessThan( myDate, yourDate ) )
// ...
As an alternative, you can overload the less-than operator (<) to compare two Date objects. This would allow you to write an expression like the following:
if( myDate < yourDate )
// ...
This format is more intuitive and convenient to use than the previous one.
You have already seen overloaded operators in many examples in the previous chapters. All of the example programs printed their output with the << operator, which is overloaded in the iostream class library.
Operator overloading is most useful when writing classes that represent numeric types. For example, scientific programs often use complex numbers; that is, numbers with a real and an imaginary component. You could write a class Complex to represent these numbers. To perform tasks like adding and multiplying complex numbers, you could write functions with names like add and mult, but this often results in lengthy statements that are hard to understand. For example:
a = mult( mult( add( b, c ), add( d, e ) ), f );
Typing an equation in this format is tedious and error-prone, and reading an unfamiliar equation in this format is even more difficult.
A better alternative is to overload the + and * operators to work on Complex objects. This results in statements like this:
a = (b + c) * (d + e) * f;
This format is easier for both the programmer writing the equation and the programmer who reads it later.