Skip to main content

Section 20.1 Importance of Operators

As a quick demonstration of the important ways operator overloads are used in C++, we will borrow an idea from the future. There is an <algorithms> library that has a sort function. It can be used on a vector to sort it:
Listing 20.1.1.
Pretty easy! (We will learn much more about sort later.)
Now let’s try the same trick with our own Time class. Don’t worry too much about time (it just stores an hour and minute). Just trying running the code.
Listing 20.1.2.
Somewhere in the wall of errors you should see error: no match for ‘operator<’. The compiler refuses to build the code because the sort function uses the < operator to compare the objects. And there is no < operator for time.
If we create an operator overload for < in Time the code will compile and run. This next sample does so. Again, don’t worry about the details yet. Just notice that there are a few lines of code for operator< and that the sort function works.
Listing 20.1.3. Time Sorting Example
Any class can be made sortable by the sort function simply by implementing an overload that defines how < works for that data type. Whoever wrote the sort code does not need to know anything about our data type other than one object of that class can be asked “are you less than this other object?”. We get to reuse the existing sort code instead of having to write a new version for our data type.
This same basic idea could be accomplished by having sortable items all implement a compareTo(other) method that the sort function relied on. Indeed, that is how languages that do not support operator overloads would approach reusing sort. But in C++, the expectation is often that generic behaviors like “less than” or “add to” will be implemented by operators.

Checkpoint 20.1.1.

Examine the logic in operator< function in Listing 20.1.3. What best describes the logic?
  • If the current Time’s hour is less than the other Time’s hour, it is <. If they have the same hour, the minutes are compared. If the current Time’s hour is greater than the other Time’s hour, it is not <.
  • If the current Time’s hour is less than the other Time’s hour, it is <. Otherwise, the minutes are compared to decide.
  • If the current Time’s minute is less than the other Time’s minute, it is <. If they have the same minute, the hours are compared.
  • If the current Time’s minute is less than the other Time’s minute, it is <. If they have the same minute, the hours are compared.
You have attempted of activities on this page.