Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I include iostream and ostream separately? [duplicate]

Tags:

c++

iostream

I've noticed that many people include iostream and ostream in C++ programs separately, like so:

#include <iostream>
#include <ostream>
int main()
{
}

Why would anyone do that? Since iostream inherits from ostream, it should include everything in it, right? Is there some obscure reason? What about simple (std::cout) code?

like image 671
jackj Avatar asked Feb 08 '11 06:02

jackj


1 Answers

Although stringstream inherits from iostream, it is not declared in the <iostream> header. The <iostream> header contains the definition of the iostream type along with the famous cout, cerr, cin, and clog types, but not other types that are iostreams (for example, file streams). For these, you do need to explicitly #include the requisite header files.

EDIT: In response to your revised question, I pulled up the C++ spec and interestingly it does not say that <iostream> has to include either <ostream> or <istream>. In fact, it could get away with just including <iosfwd>. Consequently, it's possible to #include <iostream> without actually getting a full class definition for either istream or ostream. Only explicitly including those headers can guarantee that the definitions of those classes, not just the forward-declarations, are visible.

like image 151
templatetypedef Avatar answered Oct 13 '22 13:10

templatetypedef