As the book says (Exploring C++: The Programmer's Introduction to C++):
The istream header declares input operators (>>), and ostream declares output operators(<<).
I can perfectly run the code without adding #include <ostream>
:
#include <iostream>
using namespace std;
int main()
{
cout << "hello world"<< endl;
return 0;
}
But, in book's example like:
#include <iostream>
#include <ostream> //why?
using namespace std;
int main()
{
cout << "hello world"<< endl;
return 0;
}
So, iostream
, ostream
and istream
are header files right?
If ostream
is not necessary (iostream
does the job) why does the author include it in the example? Or why does the ostream
header file still exist?
Note: In Bruce Eckel's Vol 1 book (which is published in 2000) there is nothing about ostream
or istream
. Only one header file which is iostream
.
The iostream: This class is responsible for handling both input and output stream as both istream class and ostream class is inherited into it.
istream is a general purpose input stream. cin is an example of an istream. ostream is a general purpose output stream. cout and cerr are both examples of ostreams.
ostream class − The ostream class handles the output stream in c++ programming language. These output stream objects are used to write data as a sequence of characters on the screen. cout and puts handle the out streams in c++ programming language.
14.2 Basic Structure of iostream Interaction Standard input. Standard output. Standard error. A file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With