How to initialize a forward-declared class in C++

93 Views Asked by At

I have two classes, A and B, which depend on each other:

class A {
public:
    B* b;
    A() {
        b = new B();
    }
};

class B {
public:
    A* a;
    B() = default;
};

This code will not compile because there is a circular dependency chain. However there is still an error even if I forward-declare the class B to resolve the circular dependency:

.code.tio.cpp:7:11: error: allocation of incomplete type 'B'
                b = new B();
                        ^

I believe this error is stating that I cannot initialize B because it is a forward-declared class, but I still need A and B to depend on each other, so how do I resolve this error?

1

There are 1 best solutions below

0
Jeremy Friesner On BEST ANSWER

To resolve the problem, move the body of the A() constructor to somewhere after where the full B class is defined, like this:

class B;

class A {
public:
    B* b;
    A();
};

class B {
public:
    A* a;
    B() = default;
};

A :: A() {
   b = new B();
}