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
Write a C program to compute the factorial of  5 i.e 1x2x3x4x5 etc #include stdio.h   void main()   {   char promt;      int factor;   factor = 1*2*3*4*5;   printf("The fac

Multidimensional Arrays - Every dimension is specified in separate brackets e.g. int arr[4][3]; This is a two-dimensional array with 4 as row dimension and 3 as

6999066263304447777077766622337778 -----> message sent by the first smuggler. my name is robert---------> message decoded by the second smuggler. Where ‘0’ denotes the "space".

C program to add, average and deviation of numbers: void main() {                 int sum=0,a[10],i;                 float avg=0,dev,vari=0,var;                 pri


In this problem, you will write a program that implements two algorithms for performing exact inference given a Bayesian network, namely, enumeration and variable elimination. Your

how c program starts executing?

Explain the Bit Wise Operators? C language has distinction of supporting special operators recognized as bit wise operators for manipulation of data at bit level. These operato

We can combine more than one variable on the same line i.e.   float number1,number2,number3; etc Sometimes we want to mix the variable types used on the same line, this could

Tell what the derived class inherits or doesn't inherit? A: Inherits: - All data member defined in the parent class (even though such members might not always be accessible