-4

This is a code representing a fraction with an operator overloading

class Fraction
{
private:
int _counter, _denominator;
public:
Fraction(int _x, int _y);

Fraction & operator+=(int b)
{
    _counter = _counter + b*_denominator;
    return  *this;
}

Fraction & operator-=(int b)
{
    _counter = _counter - b*_denominator;
    return  *this;
}
};

Fraction::Fraction(int _x, int _y)
{
    _counter = _x;
    _denominator = _y;
}


void main()
{
    Fraction *f = new Fraction(2, 4);

    f += 5;
}

Can someone tell me why the operator += overloading doesn't work?

Kamil Jarosz
  • 2,168
  • 2
  • 19
  • 30
Zvi vex
  • 53
  • 5

2 Answers2

2

You are overloading the operator for Fraction objects, but adding 5 to a Fraction * object - a pointer to Fraction.

Something like this would work:

(*f) += 5;
Aganju
  • 6,295
  • 1
  • 12
  • 23
1

If you implement operator+=() you should be aware of it and use it by yourself, so this code:

_counter = _counter + b*_denominator;

Is better written as:

_counter += b * _denominator;

As it is shorter and less verbose.

About the error: Use object instead of pointer, as this is not java:

int main() // main() must return int
{
   Fraction f(2, 4);
   f += 5;
}
Bryn McKerracher
  • 683
  • 6
  • 21
Slava
  • 43,454
  • 1
  • 47
  • 90