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
Program to convert fraction to decimal: int main() {                 float num, denom;     // numerator and denominator of fraction                 float value;

What is a hash function? Hash function: This is the method from the set 'K' of keys into the set 'L' of memory addresses.   H: K → L These are used to verify the address

Friend Functions One of the major features of OOP is information hiding. A class encapsulates data and methods to operate on that data in a single unit. The data from the class

how to make a game

A: BinarySearchTree.h ---------------------- #ifndef BINARY_SEARCH_TREE_H_ #define BINARY_SEARCH_TREE_H_ #include "dsexceptions.h" #include // For NULL // Binary

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

what is c++ ?

Project Description: I want an experienced programmer to program an RFID tag that will be read (maybe also written), and perform a call to a Filmmaker Pro 13 database. Skills

how to avoid duplicates strings in an array

The for Loop For loop is the controlled form of loop. The general format of this : for( initialize ; test ; update)                  {                     statements;