Iostream header versus iostream class

If there is a foo.cpp file, it usually has an associated foo.h header file with all declarations for functions defined in foo.cpp. Thus, all other files that use functions in foo.cpp can simply include the foo.h file and use them. This is my simple understanding of header files.


However, I do not see such a connection between the iostream header file and the iostream class. The iostream header file only declares a few external variables, but none of them seem to have anything to do with the iostream class. The iostream class also does not declare any new features. Why then do we have the iostream class and iostream header files? Sorry if I'm embarrassed, but this stuff really bothers me.

+4
source share
2 answers

The relationship between headers and classes is not necessarily one-to-one; that just a rule of thumb often teaches novice programmers. In fact, the C ++ language standard does not indicate any direct relationship between classes, implementation files (translation units), and headers in general, and the standard library often deviates from this rule.

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

+1
source

Templates are a special case, and you get into a problem if you declare a template class or function and define it in another file. Since C ++ compilers can only compile instances of template elements (e.g. std::vector<int> ) and not their common versions (this would be std::vector<T> ), it should have a common version available everywhere, where is the instance created. Thus, a generic class implementation is usually found in the header file.

0
source

All Articles