Overloading the ++ and — Operators in C++

The preincrement, predecrement, postincrement, and postdecrement operators can be overloaded.

The ++ and — operators may be prefix or postfix. The prefix ++var or –var first adds or subtracts 1 from the variable and then evaluates to the new value in the var. The postfix var++ or var— adds or subtracts 1 from the variable, but evaluates to the old value in the var.

If the ++ and — are implemented correctly, the following code

1 Rational r2(2, 3);
2 Rational r3 = ++r2;
// Prefix increment
3 cout << “r3 is ” << r3.toString() << endl;
4 cout <<
“r2 is ” << r2.toString() << endl;

5
6 Rational r1(
2, 3);
7 Rational r4 = r1++;
// Postfix increment
8 cout << “r1 is ” << r1.toString() << endl;
9 cout <<
“r4 is ” << r4.toString() << endl;

  • cout << “r4 is ” << r4.toString() << endl;

should display

How does C++ distinguish the prefix ++ or — function operators from the postfix ++ or — function operators? C++ defines postfix ++/— function operators with a special dummy parameter of the int type and defines the prefix ++ function operator with no parameters as follows:

Rational& operator++();

Rational operator++(int dummy)

Note that the prefix ++ and — operators are Lvalue operators, but the postfix ++ and — opera­tors are not. These prefix and postfix ++ operator functions can be implemented as follows:

1 // Prefix increment
2 Rational& Rational::operator++()
3 {
4    numerator += denominator;
5   
return *this;
6 }
7
8
// Postfix increment
9 Rational Rational::operator++(int dummy)
10 {
11    Rational temp(numerator, denominator);
12    numerator += denominator;
13   
return temp;
14 }

In the prefix ++ function, line 4 adds the denominator to the numerator. This is the new numerator for the calling object after adding 1 to the Rational object. Line 5 returns the calling object.

In the postfix ++ function, line 11 creates a temporary Rat ional object to store the original calling object. Line 12 increments the calling object. Line 13 returns the original calling object.

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 *