I admit I’m a bit naive when it comes to includes. My understanding is that if you use it in your class you either need to include it or forward declare it. But then I was going through some code and I saw this:
// file: A.cpp
#include "Helper.h"
#include "B.h"
#include "C.h"
#include "A.h"
// ...
// file: A.h
B b;
C c;
// ...
// file: B.h
Helper h;
// ...
// file: C.h
Helper h;
// ...
Can someone explain to me why B and C does not need to include Helper? Also, what are the advantages/disadvantages to organizing includes this way? (Besides the obvious less typing.)
Thanks.
When you
#includesome header (or other) file into a.cppfile, that#includestatement is simply replaced by the content of the header file. For example:After preprocessing stage, file.cpp will look like,
Can see this in g++ using
g++ -E file.cpp > TEMP, which shows you just the preprocessed files.In your present question context, you must have
#includehelper.hin/beforeB.handC.has they appear before and you declare an object of those types.Also, it’s not good practice to rely on the arrangement of header files to get the code working, because once you alter arrangement little, the whole hierarchy collapses with several compilation errors.
Instead
#includeeverything in the file if you are using it and you can use the#ifndefguards to avoid multiple inclusion: