V
Victor Bazarov
Exits Funnel said:I'm a little confused about where I should include header files and was
wondering whether there was some convention. Imagine I've written a class
foo and put the definition in foo.h and the implementation of its member
functions in foo.cpp (which obviously #inludes foo.h) and further assume
that it depends on a class bar which is defined in bar.h.
It seems that there are the following two scenarios:
1) Both foo.h and foo.cpp depend on bar.h (eg, it's an argument to a
method).
2) Only foo.cpp depends on bar.h (eg, it's used in the implementation of
one of foo's methods.
So, for scenario (1), should I #include bar.h in only foo.h or should I
also #include it in foo.cpp?
I include it in both. The simple rule is this: never rely on indirect
inclusion, always be explicit. If 'foo.cpp' needs (uses) any classes or
symbols 'bar.h' defines, include 'bar.h' into 'foo.cpp'. Same with the
'foo.h'.
I realize that assuming proper header guards in bar.h it shouldn't matter
but I'm wondering if there is a convention and if so why?
There is no convention. When it comes to using a language that has
somewhat rigit (but limited) set of rules, the rules are the only thing
everybody follows (or supposed to, anyway).
What about scenario (2)? Should I #include bar.h in only foo.cpp, only in
foo.h or in both? Again, is there a convention and if so why?
Include it [only] where it's needed.
V