1
votes

I'm kind of confused by ofstream. ofstream inherited from ostream. And it also inherited method "operator<<" from ostream.

    ofstream x;
    x << "hello world" << endl;
     //cout << "hello world" << endl;

    system("pause");
    return 0;

The above code clip is trying to use an object of ofsream to output "hello world" to the terminal just as cout did.

The above code clip can compile but shows nothing. Why does it happen?

Thanks,

3
ofstream is mainly used, when you want to output to a file. 'f' in ofstream denotes file. - cppcoder
I understand ofstream is used for writing to a file. I just curious if ofstream inherited from ostream. It also should be capable to write to terminal. - Fihop
@FihopZz: It may be capable of doing that, but that's not its default behavior. In the iostream headers, there are some platform specific things that are done in order to set cout up to write to a terminal. It doesn't happen just by calling the default constructor, which is what you are doing with your object x. - Benjamin Lindley
@BenjaminLindley, thanks. Got it. - Fihop

3 Answers

2
votes

ofstream is an abstraction for a file object. In order to be able to create a file, you need to pass in the file's name. If you don't a default ofstream object is created (which is why it compiles). By itself, such an object isn't of much use. Try:

ofstream x( "out.txt" );
x << "hello world" << endl;

...
0
votes

It's been a long time, but IIRC of stream is an output_file-stream which streams data into an opened file. For an ofstream object to actually print to the terminal you would have to make it open "/dev/console" or something similar. A plain instance of ofstream probably doesnt open /dev/console b/c you already have cout available.

-1
votes

http://en.wikipedia.org/wiki/Input/output_%28C%2B%2B%29

<iostream> contains the definition of basic_iostream class template, 
which implements formatted input and output
<fstream> contains the definitions of basic_ifstream, basic_ofstream and 
basic_fstream class templates which implement formatted input, output and input/output
on file streams.