resolving circular dependency

Sep 8, 2015 at 12:50am
Hi,
If Class A needs Class B and Class B needs Class A, what do I need to include in both header files so that the code can compile?

I tried forward declaration of class B in A's header file (class B;) and class A in B's header file but I got a forward declaration error, followed by invalid use subsequently. How should I resolve it?
Sep 8, 2015 at 12:58am
What's the error?
Sep 8, 2015 at 1:05am
Sep 8, 2015 at 2:29am
You cannot just have A includes B, and B includes A. There's no way for a compiler to decide the size of the classes.

However, you could use pointers. You can forward declare the classes, and use a pointer to B in A, and a pointer to A in B.
Sep 8, 2015 at 2:43am
The trick is to have all references to B in A's interface (the stuff that goes in the header file) to not need to know anything about B's structure.

Then in the corresponding source files (.cpp) you can properly #include both A's and B's interface headers (.h/.hpp/whatever) and do what you need.
Topic archived. No new replies allowed.