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
Study the given class specification and answer the questions that follow: class Person { private:   string name;   int yrBorn;   int yrDied;   public:   Per

for object, malloc allocates memory in heap however doesn't invoke object's constructor to initialize the object. new allocates memory & also invokes constructor to initialize the

This assignment is to be undertaken individually - no group work is permitted. Background information This assignment is an exercise in simple object-oriented programming and, acco

write a c++ program to accept 3 numbers and find the largest of 3 numbers


Project Description: I will need a tutor that would help me out in Data Structure and learning Algorithm more at the mathematical/algorithmic level. The book is written by "by T

Generate a class node that contains an integer id, a position (x, y)  and a vector of 0 5,  generate a set of  x nodes each with random connectivity n.    Implement an algorith

Write a recursive function recursiveMin that takes an integer array, a starting subscript and an ending subscript as arguments, and returns the smallest element in the array. The

Q: How can Define an Array? An Array is defined in much the alike manner as ordinary variables except that every array name must be accompanied by a size specification (that is