Tom
Tom

Reputation: 133

C++ ostream and ofstream conversions

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?

Upvotes: 13

Views: 24922

Answers (2)

biak
biak

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

user529758
user529758

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

Related Questions