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
The size of () operator This is a pseudo-operator given by the language, which returns the number of bytes taken up by a variable or data type. The value returned by this opera

FIT 3042 System Tools and Programming Languages Semester 1 2013 Assignment 1 An SDL video player for a custom video format Worth: 20% of final mark. Must be completed individually

There is a pebble merchant. He sells the pebbles, that are used for shining the floor. His main duty is to take the length of the room’s sides. But he sometimes mistakes doing that

Destructor: The purpose of destructor is to free the memory when the compiler memory is reduced or not enough to execute certain program. Sometimes there may several objects op

Write a ''C'' program to accept any 3 digit integer number from the keyboard and display the word equivalent representation of the given number.

(a) Write a recursive procedure (digits n) that computes the number of digits in the integer n using a linear recursive process. For example, (digits 42) should return 2 and (digit


Question : (a) (i) What is a structure member in C? What is the relationship between a structure member and the structure? (ii) How can structure variables be declared in C?

overload assignment opertor to assign the data of one object to anthor

The absolute land-speed record of 763.035 MPH (Mach 1.02) was set in October 15 1997 by a jet-powered car called Thrust SSC in the Black Rock Desert of northern Nevada. The team th