13. Operator Functions: Doing It with Class

After reading Chapter 12, you know how to write classes (object types) that work just like standard data types, right?

Well, almost. One of the most important features of a standard data type such as int, float, double, and even char is that you can perform operations on them. Without these operators, it would be difficult to perform any calculations in C++ at all.

C++ lets you define how to perform these same operations (such as +, -, *, and /) on objects of your own classes. You can also define how a test-for-equality is carried out, helping you determine whether two quantities are equal, as in this fragment of code:

Fraction a(1, 2), b(1, 3);if (a + b == Fraction(5, 6))    cout << "1/2 + 1/3 equals ...

Get C++ Without Fear: A Beginner’s Guide That Makes You Feel Smart, 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.