Original Post
Hi, I'm working on an RTS game and I've run into a problem where classes reference each other, and there's also some polymorphism going on so I can't seem to get it compile with any combination of #includes and forward declarations that I can think of. Here's a simplified code snippet I made that describes the problem: Right now all those classes and the main method are in different files, but I could combine them however if it would help; I could also take the "Other" reference from the parent and put it into the children - it'd be messier but if it works it's worth it. If anyone can come up with a way of arranging them and such so it compiles, that would be great, but I realize it's a strange problem, I might just have to rethink how I'm doing this. Thanks a lot for any help. [edit: added source tags -SiCrane]
class Parent {
protected:
Other *other;
public:
Parent(Other *o);
virtual ~Parent();
virtual void Foo() = 0;
virtual void Bar() = 0; };
Parent::Parent(Other *o) {other = o;}
Parent::~Parent() {}
class Child1 : public Parent {
protected:
int x;
public:
Child1(Other *o, int n);
~Child1();
void Foo();
void Bar(); };
Child1::Child1(Other *o, int n) : Parent(o) {x = n;}
Child1::~Child1() {}
void Child1::Foo() {other->Blah();}
void Child1::Bar() {}
class Child2 : public Parent {
protected:
int y;
public:
Child2(Other *o, int n);
~Child2();
void Foo();
void Bar(); };
Child2::Child2(Other *o, int n) : Parent(o) {y = n;}
Child2::~Child2() {}
void Child2::Foo() {other->Blah();}
void Child2::Bar() {}
class Other {
protected:
Parent *P;
public:
Other(int x);
~Other();
void Blah(); };
Other::Other(int x) {
if (x == 0)
P = new Child1(this, x);
else
P = new Child2(this, x); }
Other::~Other() {}
void Other::Blah() {P->Bar();}
int main() {Other o(1); return 0;}