Search code examples
c++forward-declaration

Should one use forward declarations instead of includes wherever possible?


Whenever a class declaration uses another class only as pointers, does it make sense to use a class forward declaration instead of including the headerfile in order to pre-emptively avoid problems with circular dependencies? so, instead of having:

//file C.h
#include "A.h"
#include "B.h"

class C{
    A* a;
    B b;
    ...
};

do this instead:

//file C.h
#include "B.h"

class A;

class C{
    A* a;
    B b;
    ...
};


//file C.cpp
#include "C.h"
#include "A.h"
...

Is there any reason why not to do this wherever possible?


Solution

  • The forward-declaration method is almost always better. (I can't think of a situation where including a file where you can use a forward declaration is better, but I'm not gonna say it's always better just in case).

    There are no downsides to forward-declaring classes, but I can think of some downsides for including headers unnecessarily:

    • longer compilation time, since all translation units including C.h will also include A.h, although they might not need it.

    • possibly including other headers you don't need indirectly

    • polluting the translation unit with symbols you don't need

    • you might need to recompile source files that include that header if it changes (@PeterWood)