what is the the best practice of solving circular dependency in C++
?
I could use the forward declaration, but then I get the pointer to incomplete class type is not allowed
error. Does that mean that two classes that uses each others pointer cannot be dependent?
Also, I thought about forward declaring each class and then including every header of the solution in the main.cpp
, so it's all in one place. Would you recommend it?
A snippet from the whole project is below, so you can refer to it if the issue is better explained on an example I'm familiar with, but it would do just to be theoretical. Thanks
You just need to use forward declaration correctly:
Note: Add include guards.
Its hard to actually do it without the actual declarations. The diagram is nice but does not have enough information. A picture may be worth a thousand words, but a precisely defined language can convey more exact information very compactly (unlike English and its inconsistencies).
One thought is to introduce interfaces and remove the circular dependencies. So you would have an IEffect that Effect, Player, and EffectContainer depend on. Possibly, if Player depends on certain behavior of Effect and EffectContainer depends on a different set of behavior, I would consider introducing two interfaces, effectively following the Interface Segregation Principle. This would also follow along with the Dependency Inversion Principle.
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