So, I’m having a problem where:
class A needs to know about class B, class B needs to know about C, and class C needs to know about A.
It’s essentially a circle, so I get definition errors. I tried forward declaration, but whatever’s on top, doesn’t know about what else goes on at the bottom.
How would I go about a situation like this?
Thanks
David
Assuming this is something simple, the comment above by Adam Mihalcin is correct in that the similar question answers it. But I’ll code it out anyways.
Assuming you have this (method definitions don’t matter) :
Then you can, as Adam linked to, just forward-delcare all 3 of them like this:
And put that block above all 3 of them. The important thing here though is that this is when there are pointers to the other classes, not composition where they’re a part of the class. You can use forward-declaration to allow things to compile correctly when dealing with pointers, but not with other data types. So if there was this:
With everything else the same as above, you’d need to have the “real” definition for B above the “real” definition for D. But the rest could be the same. Forward declaration only “works” for pointers.
You MUST break your dependency loop somewhere with a pointer though. If there’s never a pointer, then the data structure is “infinite” and thus doesn’t work. That’s because in my example, a D always contains a B. But what if an A always contained a B, and a B always contained a C, and a C always contained an A? Well that final A needs another B, which needs another C, which… I hope you get the idea. But with pointers, you can loop it. With composition (not pointers) it can’t loop around.