Reputation: 6352
So, we use #include
to tell the compiler/linker where to find all the relevant code for a class.
Have a look at this:
ClassC.h:
#include "ClassA.h";
ClassD.h:
#include "ClassC.h"
Let's say we use ClassA
in our ClassD
, but in a way that is in no way connected to ClassC
. We have implicitly included it by including ClassC
, so no error is thrown. However, should the code change and ClassC
is no longer needed (and we remove the #include "ClassC.h"
because of that), we'd get undefined reference error since ClassA
is now unreferenced.
Is there a way to have the compiler/linker look at each of the *.cpp and assigned *.h independently, without looking into included .h files?
If that were the case, it wouldn't look into ClassC.h
and see it includes ClassA.h
, but throw an error or at least a warning telling me that I didn't include ClassA.h
. It makes more sense since, as far as class ClassD
knows, ClassA
and ClassC
have no connection to one another (under the set assumption I'm using ClassA
independently of ClassC
).
I think that the code written that way would be much more stable and resilient to change. Wouldn't it?
Also, let's say we build a project, and it works. If we were to then reference some class(X) earlier in code than it was referenced before, we might get an error if it was using some other class(Y) that was included from some other source between that point in the program, and the previous first occurrence of that class. If we tied includes more closely to each header file that explicitly uses it, such errors would never appear.
I know I could keep track of all this myself, but it would be so easy to miss a few or more in larger projects, even medium ones. Besides, having an error/warning would make it so much easier to manage.
I know I'm complicating things a bit, but this seems a good practice to me.
It this even a good idea and can it somehow be set in compiler/linker options (e.g. GNU gcc compiler in CodeBlocks)?
Upvotes: 2
Views: 52
Reputation: 42924
Let's say we use ClassA in our ClassD, but in a way that is in no way connected to ClassC. We have implicitly included it by including ClassC, so no error is thrown. However, should the code change and ClassC is no longer needed (and we remove the #include "ClassC.h" because of that), we'd get undefined reference error since ClassA is now unreferenced.
If you need to use ClassA
in your ClassD
, then explicitly #include "ClassA.h"
in your ClassD.h
. Do not rely on implicit chains of inclusions.
Upvotes: 1