Inheritence and overloading<

I have a inheritence program where I have a Quote object and in the Quote object I overload the << operator
to handle output. When I use the operator<< with a Quote object it works perfectly.

However, I create a derived object (Quote_Sig) which is the same as the Quote but I add a field to the end of the
object. I then overload the operator<< again to handle this new field.

now when I try to print out the derived class I get the output from the base class.

==BASE CLASS==
Quote object

friend ostream& operator<< (ostream&, const Quote &);


ostream& operator<< (ostream& ostr, const Quote& q)
{
ostr<<setiosflags(ios::fixed)<<setprecision(4);
ostr<<q.TradeDate<<" "<<q.stockID<<" "<<q.expiration<<" "<<q.strike<<" "<<q.callORput<<" "<<q.root<<" "<<q.root_style<<" "<<q.symbol<<" "<<q.bid<<" "<<q.ask<<" "<<q.meanprice<<" "<<q.open_interest<<" "<<q.volume<<" "<<q.iv<<" "<<q.delta<<" "<<q.gamma<<" "<<q.theta<<" "<<q.vega<<" "<<q.rho<<" "<<q.is_interpolated<<" "<<q.status<<" "<<q.calc_date<<" "<<endl;
return ostr;
}

==DERIVED CLASS==
class Quote_sig :public Quote
{
public:
int signal;
friend ostream& operator<< (ostream&, const Quote &);
void setSignal (int);
};


==DERIVED CLASS== overloaded<<
ostream& operator<< (ostream& ostr, const Quote_sig& q)
{
ostr<<setiosflags(ios::fixed)<<setprecision(4);
ostr<<q.TradeDate<<" "<<q.stockID<<" "<<q.expiration<<" "<<q.strike<<" "<<q.callORput<<" "<<q.root<<" "<<q.root_style<<" "<<q.symbol<<" "<<q.bid<<" "<<q.ask<<" "<<q.meanprice<<" "<<q.open_interest<<" "<<q.volume<<" "<<q.iv<<" "<<q.delta<<" "<<q.gamma<<" "<<q.theta<<" "<<q.vega<<" "<<q.rho<<" "<<q.is_interpolated<<" "<<q.status<<" "<<q.calc_date<<" "<<q.signal<<endl;
return ostr;
}
While it's often useful to think of friend functions as member methods, they aren't really. The compiler see's you are calling operator<< with a reference to the base class, so it uses the operator it knows for the base class. Simple solution: Declare a protected virtual printOn(ostream&) method, and a single <<operator for a base class reference that calls the printOn method on the passed reference.
Not sure that I fully understand.

In the base class I overload the << and create a protected virtual printOn(ostream&) method

In this method I would use the overloaded << to create the ouput.

Then in the derived class I would overload the printOn(ostream&) to output the additonal field? In this overloaded printOn (ostream&), I am not sure what I would put in here.
You put the same thing there you would have otherwise put into your << operator.
Topic archived. No new replies allowed.