views:

101

answers:

2

I am trying to overload the += operator for my rational number class, but I don't believe that it's working because I always end up with the same result:

RationalNumber RationalNumber::operator+=(const RationalNumber &rhs){

   int den = denominator * rhs.denominator;

   int a = numerator * rhs.denominator;
   int b = rhs.numerator * denominator;
   int num = a+b;

   RationalNumber ratNum(num, den);
   return ratNum;
}

Inside main

//create two rational numbers
RationalNumber a(1, 3);
a.print();

RationalNumber b(6, 7);
b.print();

//test += operator
a+=(b);
a.print();

After calling a+=(b), a is still 1/3, it should be 25/21. Any ideas what I am doing wrong?

+7  A: 

operator+= is supposed to modify the object itself and return a reference. You are instead creating a new object and returning that. Something like this might work (untested code):

RationalNumber &RationalNumber::operator+=(const RationalNumber &rhs){

   int den = denominator * rhs.denominator;

   int a = numerator * rhs.denominator;
   int b = rhs.numerator * denominator;
   int num = a+b;

   numerator = num;
   denominator = den;
   return *this;
}

Likewise operator+ should return a new object and can almost always be implemented in terms of operator+=:

RationalNumber RationalNumber::operator+(const RationalNumber &rhs){
    RationalNumber tmp(*this);
    tmp += rhs;
    return tmp;
}

Finally, (now i'm getting off topic) it is usually considered best practice to use free functions instead of members where you can for things like binary operators.

Evan Teran
@starblue: thanks for the edit, good catch :-).
Evan Teran
thanks.... it works this way
+1  A: 

You are not changing the object the operator is applied to.

x += 3;

should change x.

anon