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?
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):Likewise
operator+should return a new object and can almost always be implemented in terms ofoperator+=: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.