I’ve seen a header include style like this, where header files don’t include other header files and the corresponding *.cpp files must include all the dependencies (and include them in the right order). It seems possible that in the good old days that this would make build dependency tracking easier (but I’m just guessing). Is there a good reason for it nowadays?
File “B.h”:
#ifndef _B_h_
#define _B_h_
// Note we do not #include "A.h" that contains class A declaration.
class B
{
public:
A a; // An A object.
};
#endif // _B_h_
File “B.cpp”:
#include "A.h" // Must include this before B.h, otherwise class A not defined in B.h
#include "B.h"
...
It seems whoever wrote that code misunderstood the common recommendation of reducing the number of included headers. It is usually recommended to remove unnecessary
#include <>directives in the hope of accelerating compilation. Indeed, on large projects, it may accelerate compilation significantly by:In general, people will recommend (its been on coding standards for all projects I’ve worked on) using forward declarations for classes unless the class defined in the concerned header is:
In cases 1 and 2, the
#include <>directive must appear before the class definition in all dependent source files and headers. Basically, it just moves the#include <>directive(s) from the header into each of its dependencies. It results in more code and does so with no benefit (e.g. compilation time etc. will be the same). For this reason, this recommendation is also accompanied by another entry in the coding standard: each header file should compile “stand alone” (e.g. included on the first line of a source file).