Chapter 18. Operator Overloading

Overloaded, undermanned, meant to founder, we Euchred God Almighty’s storm, bluffed the Eternal Sea!

Kipling

C++ is very good at giving you the tools to organize and use information in a way that’s most natural to you. Operator overloading is one of the features that facilitates this. It allows you to define functions to be called when ordinary C++ operators are used on the classes you’ve defined. For example, you can use operator overloading to tell C++ how to combine two boxes (a_box + b_box). (This assumes that you have a definition of what it means to add two boxes and that it makes sense to do so.) In this chapter we will go step by step through the creation of a fixed-point class and all the operators for it.

Creating a Simple Fixed-Point Class

In this section we define a fixed-point number class. Unlike floating-point numbers where the decimal point can move from place to place (0.1, 30.34, 0.0008) fixed-point numbers have a set number of digits after the decimal point.

Fixed-point numbers are very useful in applications in which speed is essential but you don’t need a lot of accuracy. For example, I’ve used fixed-point functions for color computations in the printing of color pictures. The logic had to decide which color to select for each pixel. For example, the logic had to determine whether or not to put a red dot on the paper. If the color value was more than half red, a dot was printed. So 0.95 was red and 0.23 was not. We didn’t need the ...

Get Practical C++ Programming, 2nd 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.