Operator Functions in C++

Most of the operators in C++ can be defined as functions to perform desirable operations.

It is convenient to compare two string objects using an intuitive syntax like

string1 < string2

Can you compare two Rational objects using a similar syntax like the following?

r1< r2

Yes. You can define a special function called the operator function in the class. The operator function is just like a regular function except that it must be named with keyword operator followed by the actual operator. For example, the following function header

bool operator<(const Rationa1& secondRational) const

defines the < operator function that returns true if this Rational object is less than secondRational. You can invoke the function using


or simply

r1 < r2

To use this operator, you have to add the function header for operator< in the public section in Listing 14.1 Rational.h and implement the function in the Rational.cpp in Listing 14.3 as follows:

1 bool Rational::operator<(const Rational& secondRational) const
2 {
// compareTo is already defined Rational.h
4    if (compareTo(secondRational) < 0)
return true;
7      return false;
8 }

The following code

Rational r1(4, 2);

Rational r2(2, 3);

cout << “r1 < r2 is ” << (r1.operator<(r2) ? “true” : “false”);

cout << “\nr1 < r2 is ” << ((r1 < r2) ? “true” : “false”);

cout << “\nr2 < r1 is ” << (r2.operator<(r1) ? “true” : “false”);


Note that r1.operator<(r2) is same as r1 < r2. The latter is simpler and therefore preferred.

C++ allows you to overload the operators listed in Table 14.1. Table 14.2 shows the four operators that cannot be overloaded. C++ does not allow you to create new operators.

Here is another example that overloads the binary + operator in the Rational class. Add the following function header in Rational.h in Listing 14.1.

Rational operator+(const Rationa1& secondRational) const

Implement the function in Rational.cpp in Listing 14.3 as follows:

1 Rational Rational::operator+(const Rational& secondRational) const
2 {
// add is already defined Rational.h
4    return add(secondRational);
5 }

The following code

Rational r1(4, 2);
Rational r2(
2, 3);
cout <<
“r1 + r2 is ” << (r1 + r2).toString() << endl;


Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *