Best practice to avoid Circular Dependencies in C++?

This is newb question coming from a Java guy. What is the best method for avoiding circular dependencies?

I have used forward declaration to avoid a few instances, but was looking for a ‘cleaner’ solution.

Hello darknsf,

in C++, we use #pragma once in header files, to ensure headers are include only once. ( I personnally use the #ifdef preprocessor more often, but it’s not supported in UE4 as far as I’m concern)

Also, for exemple: if a class A has a reference to a class B and in this class B with also need class A, we use forward declaration (partial inclusion for incomplete type but, perfect to use in header file)

Pragma once link 1

Pragma once link 2

Forward declaration link 1

If you need more explanations or details, just tell me I’m glad to help.

gamer08

thank you sir

I had a huge problem with errors caused by circle include dependencies of 5 classes needing access to each other. But i finally found a way to get rid of them. What i did is simply forward declare each class (exept the current one :wink: ) in the header files and put the include statements only into the .cpp files.
As long as you just have pointers or references to the “circle included” classes in the header it’s fine. In the .cpp file they can be accessed as you like it.

I hope this comment prevents some people from getting crazy like I did.

2 Likes