0

I have 2 C++ classes that need to be able to access each other's resources in a sort of parent-child relationship. I originally had the following-ish code:

A.h:

#include "B.h"

class A {
    B *pB = nullptr;
    A(B *b) {
        pB = b;
    }
    void doSomething() {
        pB->foo = 8;
    }
}

B.h:

#include "A.h"

class B {
    A *a;
    int foo = 3;
    B() {
        a = new A(this);
    }
}

I try compiling this, and I get an error inside of A.h saying:

error: 'B' does not name a type
    B *pB = nullptr
    ^

Well I google this and find it's an issue with the circular dependency, so they suggest doing forward declarations and I try implementing it by changing A.h to:

//#include "B.h"
class B;

class A {
    B *pB = nullptr;
    A(B *b) {
        pB = b;
    }
    void doSomething() {
        pB->foo = 8;
    }
}

Now I compile and get a different error in A.h saying

error: invalid use of incomplete type 'class B'
    pB->foo = 8;
      ^~
note: forward declaration of 'class B'
    class B;
          ^

Trying to google this tells me I should be including the B class. But that won't work because then I have a circular dependency and it breaks. How am I supposed to fix this properly? I thought forward declarations were supposed to be the proper way of doing it, but that doesn't work either. I tried declaring foo inside of the forward declaration and that also didn't work, and I feel would cause more issues in development. I'm using the GCC compiler, VSCode, and running on Ubuntu 20.04.

WatsonBoi
  • 121
  • 11
  • You are accessing into an incomplete type in `doSomething()`. You can circumvent this by declaring `doSomething` and defining it once `B` is fully declared. Note that this is also the way you would write a standard `C++` program. Declare stuff in the header and implement them in the source – Lala5th Apr 30 '22 at 17:26
  • 1
    You'll need to provide separate compilation units for the implementation to get this working. – πάντα ῥεῖ Apr 30 '22 at 17:27

0 Answers0