Cyclic dependencies - how to deal with them?

Hi,

I have a class GridCtrl that delegates to GridCtrlHandler but GridCtrlHandler must also be able to call methods on GridCtrl.

I cannot have GridCtrl.h #including GridCtrlHandler.h AND GridCtrlHandler.h #including GridCtrl.h, because that would create a cycle.

How can I solve this?

Regards,
Juan
The way I avoid this problem is by only including the header if I have to. If it's enough with a forward declaration I will do that instead.
(I only do this for my own classes, not for classes in other libraries)
You can forward-declare a class, but note the restrictions:
https://stackoverflow.com/questions/553682/when-can-i-use-a-forward-declaration
The problem still appears when using C++ 20 modules! there we have to import the entire module!!
There is no selective #including!!
Last edited on
It was you who mentioned header files and #includes first.

This "issue" with modules is a big question mark for me. Have the standards committee underestimated this problem or will it force me to write better code (that avoids cyclic dependencies) the day I start using modules?

The only way around this seems to be to make both GridCtrl and GridCtrlHandler part of the same module. Maybe you can use module partitions to split up the code?
Last edited on
You can make it like so:
GridCtrl.h:
1
2
3
4
5
struct GridCtrlHandler;
struct GridCtrl
{
...
};

GridCtrlHandler.h:
1
2
3
4
5
struct GridCtrl;
struct GridCtrlHandler
{
...
};

In the header you can use these forward declarations as refernece/pointer only. There is no #includ/import needed.
Heh, I created a circular dependency issue using modules and Visual Studio for once spat up a easy to understand error message:

Error	MSB8086	Cyclic build dependency detected: A.cppm depends on B.cppm depends on A.cppm.
Registered users can post here. Sign in or register to post.