Defining Nonmember Functions for Overloading Operators in C++

If an operator can be overloaded as a nonmember function, define it as a nonmember function to enable implicit type conversions.

C++ can perform certain type conversions automatically. You can define functions to enable conversions.

You can add a Rational object r1 with an integer like this:

r1 + 4

Can you add an integer with a Rational object r1 like this?

4 + r1

Naturally you would think the + operator is symmetric. However, it does not work, because the left operand is the calling object for the + operator and the left operand must be a Rational object. Here, 4 is an integer, not a Rational object. C++ does not perform automatic conver­sion in this case. To circumvent this problem, take the following two steps:

  1. Define and implement the following constructor, as discussed in the preceding section.

Rationa1(int numerator);

This constructor enables the integer to be converted to a Rational object.

  1. Define the + operator as a nonmember function in the Rational.h header file as follows:

Rational operator+(const Rationa1& r1, const Rationa1& r2)

Implement the function in Rational.cpp as follows:

1 Rational operator+(const Rational& r1, const Rational& r2)
2 {
return r1.add(r2);
4 }

Automatic type conversion to the user-defined object also works for comparison operators (<, <=, ==, !=, >, >=).

Note that the examples for the operator< and operator+ are defined as member func­tions in Section 14.3. From now on, we will define them as nonmember functions.

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 *