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?
As the name itself implies, forward declaration is just a Declaration and not a definition. So, you will declare saying the compiler that it is a class and I just declaring it here and will provide you the definition when am gonna use it. So, normally you forward declare in the Header file and #include in the .
A forward declaration is much faster to parse than a whole header file that itself may include even more header files. Also, if you change something in the header file for class B, everything including that header will have to be recompiled.
Forward declaration is used in languages that require declaration before use; it is necessary for mutual recursion in such languages, as it is impossible to define such functions (or data structures) without a forward reference in one definition: one of the functions (respectively, data structures) must be defined ...
One big benefit is faster compilation times, as a forward declaration takes less time for the compiler to parse than a complete class definition. This can make a very significant difference for large projects with many include files.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With