Matt
Matt

Reputation: 2350

Can I cast an ostream as an ofstream?

I have this code

ostream & operator<<(ostream & out, call_class & Org)
{
    for (int i = 0; i<Org.count; i++)
    {
        out << Org.call_DB[i].firstname << "  " << Org.call_DB[i].lastname
            << "  " << Org.call_DB[i].relays << "  " << Org.call_DB[i].cell_number
            << "  " << Org.call_DB[i].call_length << endl;
    }

    //Put code to OPEN and CLOSE an ofstream and print to the file "stats7_output.txt".


    return out;  //must have this statement
}

As it says i need to use an ofstream to print the contents of out to a file, can I just cast out as an ofstream and use that?

For example, would this work?

new_stream = (ofstream) out;

This is the code in the main function that calls this function

cout << MyClass << endl;

MyClass is of type call_class Assume that I cannot just change the parameter out to be of type ofstream

EDIT: Thank you for your help everybody. I know this was a difficult question to answer due to lack of clear instruction. My professor basically gave us two different versions of the same question and it was unclear what he was asking. I just wrote the data to a file outside of the function, hopefully that will be good enough.

Upvotes: 1

Views: 3970

Answers (2)

Pete Becker
Pete Becker

Reputation: 76458

The use of std::ostream, as written, is correct and idiomatic. To write to a file, just create an object of type std::ofstream and use it as the stream object:

call_class org = /* whatever */
std::ofstream str("myfile.txt");
str << org;

This works because std::ofstream is derived from std::ostream, so you can pass an std::ofstream wherever a reference to an std::ostream is expected. That's fundamental to polymorphism.

Also, in case there's still confusion, that same inserter works with any kind of std::ostream object:

call_class org = /* whatever */
std::cout << org;

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 180965

You are misunderstanding how this operator works. Since the function takes an ostream & it will work with any class that derives from ostream like ofstream. This means that all we need to do is call this function on a ofstream instance and the output will be directed to the file that instance refers to. That would look like

std::ofstream fout("some text file.txt");
call_class Org;
// populate Org
fout << Org;

Now we will output to the file stream. The output function does not care where it is outputting to, you control that from the call site. This also gives you the advantage that the same operator works with all output streams. We could replace fout with cout, some stringstream, or any other stream derived from ostream.

Upvotes: 2

Related Questions