Quick question on operator overloading

I have an adding function that involves operator overloading but when I try to run it, it gives me "right0p and left0p not declared in the scope"

1
2
3
4
5
6
7
8
Fraction operator + (const Fraction leftOp, const Fraction rightOp)
{
    Fraction temp;
    temp.num = leftOp.num * right0p.denom + leftOp.denom * right0p.num;
    temp.denom = left0p.denom * right0p.denom;

    return temp;
}
Last edited on
Firstly, you're going to kick yourself when you see the initial issue...

On lines 4 and 5, you have written left0p and right0p (with zero instead of upper-case 'o') as opposed to leftOp and rightOp respectively.

Also, you're passing your two function parameters by value here. Specifying 'const' in your current code for these parameters mean that the function cannot alter its own copy of the parameter data. While this is not really an issue in this case, I think what you may have been aiming for was to pass these parameters by const reference (see below).

1
2
3
4
5
6
7
8
Fraction operator + (const Fraction& leftOp, const Fraction& rightOp)
{
    Fraction temp;
    temp.num = leftOp.num * rightOp.denom + leftOp.denom * rightOp.num;
    temp.denom = leftOp.denom * rightOp.denom;

    return temp;
}


So you either want to pass by value (without the const type qualifier) or pass by const reference. If it is the latter, don't forget to consider the usage of the Fraction class and this operator overload function (as object data aliasing and lifetime considerations should drive your decision to pass by value or to pass by reference - this StackOverflow post provides some good insight: https://stackoverflow.com/a/4705871).

Also, are the 'num' and 'denom' members of your Fraction class public? If so, why?

It may also help for you to read through the guidance on operator overloading here: https://isocpp.org/wiki/faq/operator-overloading
Topic archived. No new replies allowed.