#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?
You need to include
fstreambecause that’s where the definition of theofstreamclass is.You’ve kind of got this backwards: since
ofstreamderives fromostream, thefstreamheader includes theiostreamheader, so you could leave outiostreamand it would still compile. But you can’t leave outfstreambecause then you don’t have a definition forofstream.Think about it this way. If I put this in
a.h:And then I make a class that derives from
Ainb.h:And then I want to write this program:
Which file would I have to include?
b.hobviously. How could I include onlya.hand expect to have a definition forB?Remember that in C and C++,
includeis literal. It literally pastes the contents of the included file where theincludestatement was. It’s not like a higher-level statement of “give me everything in this family of classes”.