Overloading Augmented Assignment Operators in C++

You can define the augmented assignment operators as functions to return a value by reference.

C++ has augmented assignment operators +=, -=, *=, /=, and %= for adding, subtracting, multiplying, dividing, and modulus a value in a variable. You can overload these operators in the Rational class.

Note that the augmented operators can be used as Lvalues. For example, the code

int x = 0;

(x += 2) += 3;

is legal. So augmented assignment operators are Lvalue operators and you should overload them to return by reference.

Here is an example that overloads the addition assignment operator +=. Add the function header in Listing 14.1, Rational.h.

Rationa1& operator+=(const Rationa1& secondRational)

Implement the function in Listing 14.3, Rational.cpp.

1 Rational& Rational::operator+=(const Rational& secondRational)
2 {
3    *
this = add(secondRational);
4   
return *this;
5 }

Line 3 invokes the add function to add the calling Rational object with the second Rational object. The result is copied to the calling object *this in line 3. The calling object is returned in line 4.

For example, the following code

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

displays

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 *