0

Right now I have two classes which both have pointers to each other. When I try to compile it has an error because the program cannot compile one class without already having compiled the other.

It works like this

  1. Main.cpp includes class A
  2. Header guard for class A
  3. Class A includes class B
  4. Class B includes class A
  5. Class A already got included so the header guard prevents loading it again
  6. Class B has no idea what class A is

I just need to be able to reference one class from the other. I'm not incredibly skilled with C++ so this may be obvious but help would be appreciated.

Wolf
  • 53
  • 6
  • If object `a` contains object `b` which contains object `a` you have an infinite object as this chain never finishes. You need to break the nested object chain by using a pointer and then you can then forward reference the class declaration to break the `#include` chain. I know this is a bit general; please read [ask] with a [mcve]. – Richard Critten Dec 31 '22 at 14:38
  • The header for class A should not need the header for class B, instead use a forward declaration. Likewise for class B and class A. – Eljay Dec 31 '22 at 14:42
  • 4
    See C++ forward declaration. There are a couple of related posts like https://stackoverflow.com/questions/553682/when-can-i-use-a-forward-declaration – ALX23z Dec 31 '22 at 14:43
  • 1
    If you have two classes that dependent on each other I have doubts your design is ok. You can have a look at dependency inversion to where you define interfaces between the classes and put them in their own header files. – Pepijn Kramer Dec 31 '22 at 14:43
  • 1
    If you can't solve it using this you will likely have to redesign: [https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes](https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes) – drescherjm Dec 31 '22 at 15:00
  • If the classes only have pointers to each other, then you don’t need their full declarations; forward declarations will do. – Andrej Podzimek Jan 01 '23 at 02:29

0 Answers0