Reputation: 133
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?
Upvotes: 13
Views: 24922
Reputation: 13
ofstream derived from ostream so
Just add some code in main.cpp
#include "ClassObject"
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ClassObject ob;
cout << ob; // print info to console window
// save info to .txt file
ofstream fileout;
fileout.open("filename.txt", ios::app);
fileout << ob;
fileout.close();
return 0;
}
Upvotes: 0
Reputation:
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.
Upvotes: 18