C++ ostream and ofstream conversions

Tom picture Tom · Mar 18, 2013 · Viewed 16.7k times · Source

My code has an ostream object that is accumulated by various modules and ultimately displayed to the console. I'd like ALSO to write this ostreamobject to a file, but do I have to rewrite all of that code using an ofstream object instead, or is there a way to convert one to the other (perhaps via a stringstream?)

For example, many of my existing functions look like

ostream& ClassObject::output(ostream& os) const
{
    os << "Details";
    return os;
}

Can I call this function with an ofstream object as the argument and have that ofstream object accumulate information instead?

Answer

user529758 picture user529758 · Mar 18, 2013

Yes, you can. That's the point in the OO concept called subtype polymorphism. Since ofstream derives from ostream, every instance of ofstream is at the same time an instance of ostream too (conceptually). So you can use it wherever an instance of ostream is expected.