Vivek
Vivek

Reputation: 2020

iostream header vs iostream class

If there is a file foo.cpp, then it usually has an associated header file foo.h with all the declarations for the functions defined in foo.cpp. That way all other files which make use of functions in the foo.cpp can just include the foo.h file and use them. Thats my simple understanding of header files.


However, I don't see such a relation between the iostream header file and the iostream class. The iostream header file only declares a few extern variables but none of them seem to have have anything to do with the iostream class directly. The iostream class also doesn't seem to declare any new functions. Why do we then have the iostream class and the iostream header files? Apologies if I sound confused, but this stuff really confuses me.

Upvotes: 4

Views: 832

Answers (2)

Fred Foo
Fred Foo

Reputation: 363627

The relation between headers and classes isn't necessarily one-to-one; that's just a rule of thumb often taught to novice programmers. In fact, the C++ language standard does not specify any direct relation between classes, implementation files (translation units), and headers at all and the standard library often deviates from this rule.

std::iostream is a typedef for the template class std::basic_iostream (specifically, for basic_iostream<char>). On my platform, <iostream> includes <istream> which defines basic_iostream, as well as <iosfwd> which contains the typedef.

Upvotes: 1

zneak
zneak

Reputation: 138071

Templates are a special case and you get into trouble if you declare a templated class or function and define it in another file. Since C++ compilers can only compile instantiations of templated elements (like std::vector<int>) and not their generic versions (that would be std::vector<T>), it needs to have the generic version available wherever an instantiation is made. Therefore, the implementation of a generic class is generally in its header file.

Upvotes: 0

Related Questions