O'Reilly logo

C++ Without Fear: A Beginner’s Guide That Makes You Feel Smart, Third Edition by Brian Overland

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

18. Operator Functions: Doing It with Class

One of the more interesting things you can do with C++ is to define how operators work with objects of your classes. You can define a Fraction type, for example, and then create a way for the following statements to be meaningful in C++:

Fraction fr1(1, 2), fr2(1, 4);cout << fr1 + fr2 << endl;

Wouldn’t it be nice if this would add 1/2 to 1/4 and then print the characters “3/4”? Well, you can make C++ do just that. And you can make such code even more readable by adding the Fraction(string) constructor shown at the end of Chapter 11. In that case, you can write this:

Fraction a = "1/2", b = "1/6";cout << a + b << endl;   // Print "2/3".

In this ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required