2

Today, a colleague inquired if there is a technical reason to #include headers before forward declaring a class in a header. Specifically, I'm not interested in the order of #includes within themselves or the merits of forward declare vs #includes, but on any technical reasons one order is preferred over the other.

Example: Assume companions.h is correct in that it requires donna.h and clara.h to be #include and CSpaceTimeContinuum and CTardis can be forward declared. Is it better to #include then forward declare?

// companions.h
#include "donna.h"
#include "clara.h"
class CSpaceTimeContinuum;
class CTardis;

or forward declare then #include?

// companions.h
class CSpaceTimeContinuum;
class CTardis;
#include "donna.h"
#include "clara.h"

If there's no technical difference and it is a stylistic thing only, I would be happy to learn that as well. Thank you!

Kevin K
  • 408
  • 2
  • 18
  • 2
    Not a strong argument here, more a habit: Includes come on the very top for me, so actual "hand written" contents of the file always below them. I'd not spontaneously look for code above `#include `. But that may just be me. – Peter - Reinstate Monica Apr 13 '15 at 13:43
  • Wait... is this question JUST about ordering of unrelated `#include`s and forward declarations? `CTardis` here has nothing to do with `donna.h` or `clara.h`? – Barry Apr 13 '15 at 13:49

2 Answers2

3

Always headers first, then forward declares. Otherwise you risk unnecessary dependencies such that you'll need to repeat the forward declares whenever you include donna.h, for example (because you have inadvertently introduced a need for it).

Daniel Lidström
  • 9,930
  • 1
  • 27
  • 35
  • 1
    Could you add an example of what you're describing ? – Quentin Apr 13 '15 at 13:45
  • I do have an answer to a similar question here: http://stackoverflow.com/a/3935468/286406. There I try to describe the way I would structure my code with forward declares, public and private header files and the .cpp files themselves. Hope this helps! – Daniel Lidström Apr 14 '15 at 06:57
0

"donna.h" and "clara.h" should be constructed so they do no depend on external forward declarations, which leaves just one practical possibility that there could be a collision between CSpaceTimeContinuum and CTardis declared in any of those files and your usage of those classes in the local source. The only difference then in order of lines could make is diagnostics in case of collision.

ArunasR
  • 1,907
  • 1
  • 14
  • 15