C++ ostream and ofstream conversions

c++, ofstream

Solution

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.

Problem

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 `ostream`object 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?

Original source