Suppose I have a file X.h which defines a class X, whose methods are implemented in X.cc.
The file X.h includes a file Y.h because it needs Y to define class X. In X.cc, we can refer
to Y because X.h has already included Y.h. Should I still include Y.h in X.cc ?
I understand that I don’t need to and I can depend on header guards to prevent multiple inclusions.
But on the one hand, including Y.h makes X.cc a little more independent of X.h (can’t be
completely independent of course). What is the accepted practice?
Another example: including <iostream> in both .h and .cc files. I see some people do this
and some don’t.
Be minimal. In headers, prefer forward declarations to full definitions. Use
iosfwdinstead ofostream, for example.That said, X.h and X.cc represent the same logical unit. If your dependency on Y.h ever changed (for example, turned it into a forward declaration), you’d be changing the class anyway. So you can move
#include "Y.h"to X.cc justifiably.In other words, X.cc and X.h go hand in hand. X.cc can reliably assume what’s in X.h. So there’s no need to re-include something if X.h does.
Dependencies where you ‘include it anyway’ occur with resources other than your own. For example, if you needed Z.h, you’d include it even if Y.h does. X.h does not get to reliably assume the contents of Y.h because X.h doesn’t go with Y.h, it uses it.