C++: including a class definition in a header file

c++, class, header

Solution

Declarations (stating that something exists) that need to be seen in more than one cpp file should go in header files. Declarations that are local to a single cpp file should be in the cpp file itself.

Definitions (providing the body of a function or allocating/initializing variables) should usually go in cpp files, but not always.

The question you need to understand is does the compiler have enough information to do its job if it has seen the header file and not the corresponding cpp file.

For example: you can call a method if the compiler has seen the declaration (the method prototype) -- unless the method is generic (a templated method or a member of a templated class) or inline in which case the compiler needs to have seen the definition (the method body) too.

Therefore normal methods go in cpp files; templated methods go in header files; inline methods go in header files (and so on).

There are other situations in which definitions belong in header files including static member constants. It all comes back to giving the compiler the information it needs one one hand vs minimizing coupling between separate compilable units on the other. Again there are no hard-and-fast rules, just guidelines coupled with the knowledge and experience of the developer writing the code.

Problem

A number of posts are pretty adamant that source code should not go in a header and that header files should be kept to a minimum. I've been sticking to this with my own code, but I want to use someone else's code to achieve a particular goal (the code is documented here http://ftp.arl.mil/random/). I notice that this is basically one giant header file which defines a class. Is it OK to leave this in a header file? Should I copy it all to a .cpp file and create a new .h that just declares the functions, structures etc? If I split it into a .cpp and a .h as I propose, will it work? Or do classes need to be in the header to be accessed by all source code?

Original source

Related problems