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
implementation of the power and factorial in programs

T o k e n :  Tokens  are  small  entities  in  a  program.    Example: identifiers,  keywords,  constants, operators, strings, etc.  These tokens are used almost in same wa


Q: Can I overload operator == so it allow me compare two char[] by a string comparison? A: No: at least one operand of particular overloaded operator should be of some user-defi

accept principal amount,rate of interest, & duration from the user. display interest amount and total amount

write a program for convert numbers upto 9 to alphabet?Eg.now enter the inputis 666 means output is "0" lphabet

What is the difference among a copy constructor and an overloaded assignment operator? Ans) A copy constructor constructs a latest object by using the content of the argument

Polymorphism C++ supports this idea - that different objects do "the right thing "- by function polymorphism and class polymorphism. Poly means many, while morph means form.

Overloading Binary Operators Using Friend Function class SI {float i,p,n,r,a; public: SI(){}; SI(int gp,int gn, int gr); void putdata(void); friend SI operato

string will contain only lower case alphabet& the ascii value starts from 1-26,(ie,a=1&z=26).it perform the operation like the following costs:add=2units,replace=1unit,delete=3unit