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
is getchar() is a C++ library function?

Using the Constructor There are basically three ways of creating and initializing the object. The first way to call the constructor is explicitly as :

smugglers are becoming very smart day by day. Now they have developed a new technique of sending their messages from one smuggler to another. In their new technology, they are send

The Malt Shop restaurant charges $2.99 for burgers, $1.29 for fries, and $1.25 for sodas.  Write a program that allows a restaurant employee to enter an order (the number of bur


What is inheritance? Class, the vehicle, which is used to execute object-oriented concepts in C++, has given a new dimension to this idea of reusability. Many vendors now offer

Project Description: I have a barber salon I am seeking someone to build me software for my PARTNER PT6910 touch screen till system. This software must add multiple staff login

switch statement

WAP TO PRINT SUM=1!+2!+3!+4!+....N! #include stdio.h> #include conio.h>   void main() {                    int n,i;                    float sum=0,fac

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