Skip to main content

Section 20.7 Other Operator Overloads

Remember that the primary goal of this book is β€œlearn to program using C++”, not β€œlearn C++ programming”. Operator overloading is not unique to C++, but C++ is fairly unique in how much it depends the technique. At this point, we have covered the ideas you will need need in this book. But there are other ways to overload operators and other operators that can be overloaded. Below is a teaser of some other things that can be done.
Operator overloads can be written as non-member functions. For example, instead of `bool Rational::operator==(const Rational& other)`, we can define it as a non-member function:
bool operator==(const Rational& r1, const Rational& r2);
With that version of ==, the compiler will see r1 == r2 as operator==(r1, r2).
Writing operators as non-member functions can provide more flexibility to compare different types of data - like writing an == to check if an ints is equal to a Rational. It is also required for some operators.
One such operator is the << operator (stream insertion operator), which is used for output streaming. Instead of having to write cout << r1.toString() we can just write cout << r1 if we define an operator that looks like:
std::ostream& operator<<(std::ostream& os, const Rational& r);
You can overload the [] operator (subscript) to make an object behave like a string/vector/array. This can be useful for accessing elements in an object that stores a collection of values.
In a similar fashion, you can override the () operator to allow an object to be called like a function. An object that can be called as if it is a function is sometimes referred to as a functor.
Should you be interested in learning more about any of these, LearnCPP is a good place to learn more.
You have attempted of activities on this page.