Imagine if there is an abstract class with a method (say output or print) which would be inherited by a few other classes. Later objects are created using the inherited classes, and the user wishes to call the above method twice, for eg (i) output/print to screen and (ii) output/print to a file.

what is the best way to achieve that.

October 2nd, 2013, 10:03 PM

laserlight

Re: Polymorphic Methods in Abstract class

If by "print to screen" you mean "print to standard output", then one approach is:

This way, subclasses of A can override the print method to do the printing they require. Users of the class and its subclasses then use the overloaded operator<< whether with std::cout or some std::ofstream as the case may be.

After creating objects of chair and *other furniture classes, I would like to call the print method twice, one to print the object in a standard stream, and one in a file stream, I really don;t know what to do. I mean how to best achieve that.

After creating objects of chair and *other furniture classes, I would like to call the print method twice, one to print the object in a standard stream, and one in a file stream, I really don;t know what to do. I mean how to best achieve that.

Have your print() function accept a pointer or reference to a std::ostream.

Code:

void print(std::ostream& strm)
{
strm << "This is a chair";
}

//...
print(cout);
std::ofstream ofs("Test.txt");
print(ofs);

Regards,

Paul McKenzie

October 5th, 2013, 09:05 PM

rockx

Re: Polymorphic Methods in Abstract class

so where do i implement this, in class Furniture or class Chair or the main?

October 6th, 2013, 04:16 AM

laserlight

Re: Polymorphic Methods in Abstract class

Look at my example: I declared the function as pure virtual in the base class. What I did not show was that the virtual function was then defined in the derived classes, but that should be obvious since I wrote that "subclasses of A can override the print method to do the printing they require".

October 7th, 2013, 06:21 AM

Igor Vartanov

Re: Polymorphic Methods in Abstract class

Quote:

Originally Posted by rockx

Imagine if there is an abstract class with a method (say output or print) which would be inherited by a few other classes. Later objects are created using the inherited classes, and the user wishes to call the above method twice, for eg (i) output/print to screen and (ii) output/print to a file.

Don't you see that polymorphism of outputting mechanism generally has nothing to do with the polymorphism/abstractness of your class hierarchy? Those two aspects are pretty independent of each other. Your hierarchy polymorphism basically controls what to output ('Furniture' vs 'Chair'), while outputting polymorphism controls how/where to output (screen vs file).