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
Binary search in array: - C program: Write a program in c to define binary search in array. void main()                 {                 clrscr();

Operators in C++: All C operators are valid operators in C++ also.  Besides C++ has developed some new operators like Operators and their Expression: 1.      Logical op

Draw a flowchart for a program that allows the user to enter 20 names along with their ages and their Social Security Numbers in three parallel arrays. Programs shou

Write a program called A1Q3, that reads it the radius of a circle as an integer and prints the circle's diameter, circumference and area.  Use a constant value for pi.  Do all calc

Define Commonly Used Built-in Library Functions? Comprise opened a file pointer you will desire to use it for either input or output. The C language supplies a set of functions

A palindrome is a string that reads the same from both the ends. Given a string S convert it to a palindrome by doing character replacement. Your task is to convert S to palindrome

write a c++ program, that finds the minimum total number of shelves, including the initial one, required for this loading process.


What are  Id e n t i f ie rs a n d C o n s t a n ts in C++? Id e n t i f ie r a n d C o n s t a n t : I d e n t i f ie r

THEORY OF A COMPUTER PROGRAMMING