Search code examples
c++classcompiler-errorsincludeforward-declaration

C++ include loop. Can't use forward declarations


I want to do something like this, running from main():

Main.cpp

#include "A.h"
#include "B.h"
int main(){
    A* a = new A();
    B* b = new B(a);
    b->render();
    return 0;

A.h

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

A.cpp

#include "A.h"
void renderObject(B* b) {
    int* data = b->data;
    //do something with data

B.h

class A;
class B {
public:
    A* a;
    B(A* a);
    int* data;
    void render();
}

B.cpp

#include "B.h"
B(A* a) {
    this->a = a;
    //something that write stuff to data.
}
void render() {
    a->renderObject(this);
}

Is this kind of coding possible? What can I do so that both can reference to both?


Solution

  • For this line in A.cpp you need more than "it is a class", the information provided by a forward declaration.
    I.e. in this file you need an additional

    #include "B.h"
    

    Similar for B.cpp, it needs to include A.h for the contained code. (Thanks, Scheff.)

    And, at least if only looking at the shown code, you do not really need to include A.h in A.cpp. This already changes if you add the seemingly missing A:: and the rest of the actual file very likely needs it.