Question about header files in C++: when I should use them. If I write small program should I create header file or can I just declare my classes in .cpp files? What is a good practice? If you give links to articles about it, it would be good. I could not find good ones.
Share
Use header files when you need to share information between several source files. The header file, used carefully, will ensure consistency between a file defining some functionality and other files using that functionality.
When a program consists of a single (source) file, there is no need to create a header. When a program needs more than one source file (say two source files), there must be at least one function or variable ‘shared’ between the two files (because if there wasn’t, one of the files would be redundant). You should have a header to describe the shared function or variables so that the producer and consumer agree on the common functionality.
The corollary is that a header should not describe anything not needed by the consumers of the functionality. Just because the implementation needs to use some second header, the consumer should not be made to include it. If the second header provides definitions used in the interface, then it should indeed be included in the common header.
OK – lots of verbiage. A concrete example:
source1.h
source1.cpp
program.cpp
The header here is necessary to provide the assurance that everything is consistent. Both
source1.cppandprogram.cppmust include the header to ensure the consistency.Note that if
somefunc()was defined inprogram.cppthere would be no point in providing the header.Now suppose we modify
somefunc():source1.cpp – revised
Superficially, you could revise
source1.hso it includes<iostream>, but that would be a bad move. The interface of the function defined,somefunc(), does not depend on<iostream>, so the header should not include<iostream>.