4

I've given this a lot of thought (honestly) - since last semester. And I'm still not entirely sure what is going on here. Would anyone be able to help and enlighten me? I'm ok with the pre/postfix difference. It's how the hell the fraction is being incremented which is confusing the hell out me

take the prefix example for instance. So if I had a fraction which was 2/4 would that increase to 3/4? Because when I look at numer += denom, it makes me think that it will return 2+2+4, which is 8.

// prefix increment operator
fraction& fraction::operator++() {
    numer += denom;
    return *this;
}

// postfix increment operator
fraction fraction::operator++(int) {        // Note dummy int argument
    fraction temp(*this);
    ++*this;                            // call the prefix operator
    return temp;

thanks heaps in advance :)

jewfro
  • 253
  • 1
  • 5
  • 15
  • Why 2+2+4? `numer` is 2 and `denom` is 4. Therefore, `numer += denom;` makes `numer` 6. – chris Jul 26 '13 at 07:58

1 Answers1

3

The prefix function would spell out to

numer = numer + denom;

so in case of 2/4 it would be numer = 2 + 4 = 6 so the result would be 6/4 (since denom remains unchanged). Since n/n = 1 for all integers (except 0), (a+n)/n will always be an increase by 1.

The postfix version uses the prefix version to do the calculation explained above.

nikolas
  • 8,707
  • 9
  • 50
  • 70
  • 1
    You might point out explicitly that this is the equivalent of adding `1` to the number. (At least for positive numbers; I have my doubts as to whether the algorithm works if `denom` is negative.) – James Kanze Jul 26 '13 at 08:02
  • @JamesKanze True. But I'd expect most fraction implementations to store the sign in the numerator only. – Angew is no longer proud of SO Jul 26 '13 at 08:03
  • @JamesKanze Thanks for the suggestion, adopted it. – nikolas Jul 26 '13 at 08:05
  • @Angew I would expect most fraction implementations to "normalize" the representation, with no common denominators, and the sign in the numerator only. But since the example given is 2/4, which is not normalized, I'm not sure, and I thought it worth pointing out. – James Kanze Jul 26 '13 at 08:26
  • @JamesKanze Why wouldn't the algorithm work if `denom` is negative? `(a+n)/n = a/n + n/n = a/n + 1`, or at a concrete example `1/(-2)++ = (1+(-2))/(-2) = (-1)/(-2) = 1/2` – nikolas Jul 26 '13 at 08:31
  • @nijansen Good point. Maybe it would work. It just wasn't as obvious as when `denom` is positive. – James Kanze Jul 26 '13 at 10:08