Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

How can I provide printing for an entire hierarchy rooted at “class X”?

0
0 Posted

How can I provide printing for an entire hierarchy rooted at “class X”?

0
0

Provide a friend operator<< that calls a protected virtual function: class X { protected: virtual void print(ostream& o) const; //or "=0;" if "X" is abstract public: friend ostream& operator<<(ostream& o,const X& x) {x.print(o); return o;} //... }; Now all subclasses of X merely provide their own "print(ostream&)const" member function, and they all share the common "<<" operator. Friends don't bind dynamically, but this technique makes them *act* as if they were.

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123