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 of classes?

0
Posted

How can I provide printing for an entire hierarchy of classes?

0

Provide a friend operator<< that calls a protected virtual function: class Base { public: friend ostream& operator<< (ostream& o, const Base& b); // ... protected: virtual void print(ostream& o) const; }; inline ostream& operator<< (ostream& o, const Base& b) { b.print(o); return o; } class Derived : public Base { protected: virtual void print(ostream& o) const; }; The end result is that operator<< acts as if it was dynamically bound, even though it's a friend function. This is called the Virtual Friend Function Idiom. Note that derived classes override print(ostream&) const. In particular, they do not provide their own operator<<. Naturally if Base is an ABC, Base::print(ostream&) const can be declared pure virtual using the "= 0" syntax.

Related Questions

What is your question?

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

Experts123