Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 474
Mat Avatar asked Mar 28 '12 11:03

Mat


People also ask

Should I use forward declaration or include?

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 .

Why forward declaration instead of include?

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.

When use forward declaration?

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 ...

What is the advantage of forward declaration?

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.


1 Answers

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)

like image 58
Luchian Grigore Avatar answered Oct 06 '22 01:10

Luchian Grigore