I'm trying to compile something like the following:
A.h
#include "B.h"
class A {
B * b;
void oneMethod();
void otherMethod();
};
A.cpp
#include "A.h"
void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}
B.h
#include "A.h"
class B {
A * a;
void oneMethod();
void otherMethod();
};
B.cpp
#include "B.h"
void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}
Until now I haven't had problems using forward declarations, but I can use that now, because i can't use atributtes or methods of only-forward-declarated classes.
How can I solve this?
In C++, unlike Java and C#, you can define a member function (providing its body) outside the class.
class A;
class B;
class A {
B * b;
void oneMethod();
void otherMethod() {}
};
class B {
A * a;
void oneMethod();
void otherMethod() {}
};
inline void A::oneMethod() { b->otherMethod(); }
inline void B::oneMethod() { a->otherMethod(); }
As long as I'm understanding your question right, all you need to do is this:
A.h
class B;// Forward declaration, the header only needs to know that B exists
class A {
B * b;
void oneMethod();
void otherMethod();
};
A.cpp
#include "A.h"
#include "B.h"//Include in the .cpp since it is only compiled once, thus avoiding circular dependency
void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}
B.h
class A;// Forward declaration, the header only needs to know that A exists
class B {
A * a;
void oneMethod();
void otherMethod();
};
B.cpp
#include "B.h"
#include "A.h"//Include in the .cpp since it is only compiled once, thus avoiding circular dependency
void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With