Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to include both the iostream and fstream headers to open a file

Tags:

c++

iostream

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("test.txt");
  return 0;
}

fstream is derived from iostream, why should we include both in the code above?

I removed fstream, however, there is an error with ofstream. My question is ofstream is derived from ostream, why fstream is needed to make it compile?

like image 743
skydoor Avatar asked Mar 16 '10 02:03

skydoor


People also ask

What is the difference between iostream and fstream?

An iostream is a stream which you can write to and read from, you probably won't be using them much on their own. An fstream is an iostream which writes to and reads from a file.

Does fstream open a file?

Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only. Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.

What does #include fstream do in C++?

<fstream> library provides functions for files, and we should simply add #include <fstream> directives at the start of our program. To open a file, a filestream object should first be created. This is either an ofstream object for writing, or an ifstream object for reading.

Which of the following function is used to open a file in C++?

Explanation: C++ allows to use one or more file opening mode in a single open() method. ios::in and ios::out are input and output file opening mode respectively.


1 Answers

You need to include fstream because that's where the definition of the ofstream class is.

You've kind of got this backwards: since ofstream derives from ostream, the fstream header includes the iostream header, so you could leave out iostream and it would still compile. But you can't leave out fstream because then you don't have a definition for ofstream.

Think about it this way. If I put this in a.h:

class A {
  public:
    A();
    foo();
};

And then I make a class that derives from A in b.h:

#include <a.h>

class B : public A {
  public:
    B();
    bar();
};

And then I want to write this program:

int main()
{
  B b;
  b.bar();

  return 0;
}

Which file would I have to include? b.h obviously. How could I include only a.h and expect to have a definition for B?

Remember that in C and C++, include is literal. It literally pastes the contents of the included file where the include statement was. It's not like a higher-level statement of "give me everything in this family of classes".

like image 181
Tyler McHenry Avatar answered Oct 07 '22 16:10

Tyler McHenry