How can i provide printing for whole hierarchy of classes?, C/C++ Programming

A: Provide a friend operator<< which calls a protected virtual function

class Base {

public:

friend std::ostream& operator<< (std::ostream& o, const Base& b);

... protected:

virtual void printOn(std::ostream& o) const;

};

inline std::ostream& operator<< (std::ostream& o, const Base& b)

{ b.printOn(o); return o;

}

class Derived : public Base {

protected:

virtual void printOn(std::ostream& o) const;

};

The ending result is that operator<< acts as if it were bound dynamically, even though it's a friend function. It is called the Virtual Friend Function Idiom.

Note down that derived classes override printOn(std::ostream&) const. Particularly, they do not provide their own operator<<.

Of course if Base is an ABC, Base::printOn(std::ostream&) const may be declared pure virtual using the "= 0" syntax.

!    

 

Posted Date: 3/20/2013 8:15:59 AM | Location : United States







Related Discussions:- How can i provide printing for whole hierarchy of classes?, Assignment Help, Ask Question on How can i provide printing for whole hierarchy of classes?, Get Answer, Expert's Help, How can i provide printing for whole hierarchy of classes? Discussions

Write discussion on How can i provide printing for whole hierarchy of classes?
Your posts are moderated
Related Questions
Explain about the String Constants in c language? A collection of characters included within a pair of double quotes is treated as string constant. The character may be numbers

why c is middle level language?

Define the Classification of Operators in C Language? Depending on the function performed the operator can be classified as 1. Arithmetic Operator 2. Logical Operator 3. Inc

What I need is an auto-click bot. The auto-click bot would ask me for a url(or it would be pre-defined too) so that it loads that specific url and click an ad automatically. This w

You are to implement a code cracking system. The system will deploy four processes (p1,p2,p3 & p4) to try to guess the password of an encrypted code. For encryption, we consider th

how to use nested loop of for in array

A: A smart pointer is a C++ class which mimics a regular pointer in syntax and some semantics, however it does more. Since smart pointers to distinct types of objects tend to have

To develop a web crawler such that when given a base URL, it will traverse the entire web tree and then build an index of keywords and what URL link they appear on.   The web crawl

Need help in network programming in C++ project. How much you charge?

Define the Volatile Keyword Qualifiers in C Language? The volatile keyword proceed as a data type qualifier and a volatile variable is for dynamic use. E.G. for data that is to