Let’s say I have 2 classses:
// a.h
#ifndef A_H
#define A_H
#include "b.h"
class A {
public: void a() {
B* b = new B(this);
}
}
#endif
// b.h
#ifndef B_H
#define B_H
#include "a.h"
class B {
public: B(A* a) {
// ...
}
}
#endif
This code will raise error A has not been declared because class A references class B, which in turn references class A that hasn’t been declared in a.h yet.
So how can I pass an instance of A to B?
You need to
Bconstructor to pointer or reference*B::Bto the cpp file (this removes any direct dependency on the definition ofA, and allows you toforward declare
Ain B.h :Note that I added a
constqualifier for theA&constructor parameter, as I assume you don’t want to modifyain the constructor ofB.Of course, you can also play this the other way around, by moving the definition of
A::aand the corresponding#include "b.h"into a.cpp.*You should most likely do this anyway, as it is highly unlikely you wanted to pass an
Aobject by value there. Passing an object by value means implicitly creating a copy of the object and pushing that onto the stack. Which