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
Define the Bitwise-Exclusive-OR Operator: ^: The bitwise-exclusive-OR operator (^) compares every bit of its first operand to the corresponding bit of its second operand. If on

What is memory allocation? Memory Allocation : It is the method of allocating memory storage to program in such that the program can be run.


Data array A has data series from 1,000,000 to 1 with step size 1, which is in perfect decreasing order. Data array B has data series from 1 to 1,000,000, which is in random order.


A: Provided that function parameter is "const reference", compiler create temporary variable in following two ways. a) The actual argument is the correct type, however it isn't

Step 1 Define the program headers and the variables      #include   #include   #include   #include void main()   {       char prompt;     float a,b,c,d,e;     floa

Stage One Define the specification of the program            Add two nxm size matrices   Stage Two Divide the program up into separate modules           Input Matrix         Ad

Need help with C network program

Program is to store marks and name, roll no in a file: class stud   {     int rno;     char name[20];     int m1,m2,m3;     public:                 void acce