iostream vs ostream what is different?
In C++11, as specified by the standard in §27.4.1, the header iostream
includes the istream
and ostream
headers in itself, so the #include <ostream>
is redundant.
The 'synopsis' of iostream
given by the standard in the aforementioned section is
#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>
namespace std {
extern istream cin;
extern ostream cout;
extern ostream cerr;
extern ostream clog;
extern wistream wcin;
extern wostream wcout;
extern wostream wcerr;
extern wostream wclog;
}
You need #include <iostream>
to get access to the standard stream objects such as cout
. The author of that code is making sure to not rely on the implementation detail that <iostream>
includes <ostream>
(that wasn't guaranteed prior to C++11).
You need <ostream>
to get access to operator <<
and std::endl
.
As ildjarn noted in the comment, C++ standard from 2003 says that iostream does not necessary include istream and ostream. So, theoretically, the book is correct.
However, most major compiler vendors have added istream and ostream into iostream, so your code works on the compiler you are using. You might not have such luck on some other compiler.
If you want to write portable code that would compile on older compilers that only adhere to 2003 standard (or earlier), you should include both headers. OTOH, if you are the only one compiling your code and have control which compilers would be used, it's safe to use iostream only, because that is forward-compatible.