Including classes in header vs forward declaration in header and include in cpp

Hi,

When I need to use something that needs to also be declared in the header, let’s say a member variable of some specific scene component, I’ve always included the header of the component in my header and that was it. It was then available in both my header and my .cpp for use. Recently, I’ve noticed that in the Unreal’s internal classes, it’s usually done such that there’s only forward declaration of the class in the header, and the actual inclusion of the header happens in C++.

For example, what I do
.h:



#include "Components/CapsuleComponent.h"

UCapsuleComponent* Capsule;


.cpp:



Capsule->InitCapsuleSize(50.0f, 100.0f);


What Epic does:
.h:



class UCapsuleComponent;

UCapsuleComponent* Capsule;


.cpp:



#include "Components/CapsuleComponent.h"

Capsule->InitCapsuleSize(50.0f, 100.0f);


I wonder what is the reason to do it this other way? Performance… or…?
Thanks in advance.

It helps speed up compile times by reducing dependencies for header changes. It can also help resolve situations where 2 classes include each other.

http://jatinganhotra.com/blog/2012/11/25/forward-class-declaration-in-c-plus-plus/

Ah, thanks… Yes, the circular dependency is something I’ve already ran into, so this will come in handy :slight_smile:

As a rule, I tend to favor forward declaration as much as the compiler will allow. It speeds up my compile times significantly.

Does it affect gameplay at all in the end or is it just for the compile time?

No impact on gameplay since that is using an executable (the product of the link stage). By the time you have an executable or even object code within the compilation and link, the methods used to resolve source references are already resolved. The compiler just needs references resolved to generate object code.