Include in header file vs. forward-declare and include in .cpp [duplicate]

Your first way of doing it means that in a.h, the existence of class B is known, but not its definition. This limits what you can do with B inside a.h. For example, you can have variables of type B *, but not variables of type B (because for a declaration of a variable of type B the compiler must be able to see the full definition of B). Also, if you have variables of type B *, you can’t dereference the pointer (because for that, too, the definition of B must be known).

Therefore, your second choice – which doesn’t have these problems – is preferred, and this is what most people use most of the time.

It’s only special cases in which the first method may be useful. For example:

  • If the .h files include each other (but then you may get a number of further problems, also regarding include-guards; this is generally difficult and to be avoided);
  • If b.h is extremely large and complex, so you’d like to avoid including it wherever possible because it slows down the compilation process.

Leave a Comment