Inheritence ambiguity paradoxical behavior

I observed a peculiar effect.
I have a superclass called Fraction and a derived class called MixedNumber.
I overloaded << in both classes.
I overloaded * in both classes.
If I declare m1 and m2 to be MixedNumbers (i.e., in the derived class),
cout<<(m1*m2) is outputted as if the compiler understood it as printing out members of the Fraction class.
HOWEVER, if I declare m3 to be a MixedNumber and write
m3=m1*m2 and then write
cout<<m3, it is outputted as if it were in the MixedNumber class.
Any thoughts?
To see the full project, please visit this link:
http://www.qlineorientalist.com/CTutorial/?p=765
does m1*m2 return a MixedNumber?

EDIT:

Ah.. your problem is here:

1
2
3
4
5
class MixedNumber : public Fraction
{
// friend ostream &operator<<(ostream &, MixedNumber &);  // BAD

friend ostream &operator<<(ostream &,const MixedNumber &); // GOOD 


It's a const correctness thing. Temporary objects (returned from the * operator) can't be passed by non-const reference. So MixedNumber's << operator can't be called.

Fraction's << operator does take a const reference, though, so it can be called. Which is why it was being called instead.
Last edited on
Topic archived. No new replies allowed.