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
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.