Hello,
I've got a - I believe - pretty common problem but I can't figure it out. I've got two different classes which I want both to hold an instance of each other. Here's my code;
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include "MyClass1.cpp"
#include "MyClass2.cpp"
int main()
{
MyClass1 c1;
MyClass2 c2;
c1.setC2(&c2);
c2.setC1(&c1);
return 0;
}
|
MyClass1.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class MyClass2;
class MyClass1
{
private:
MyClass2 *m_c2;
public:
void setC2(MyClass2 *c) { m_c2 = c; }
int getC2Number() { return m_c2->returnNumber(); }
int returnNumber() { return 100; }
};
|
MyClass2.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class MyClass1;
class MyClass2
{
private:
MyClass1 *m_c1;
public:
void setC1(MyClass1 *c) { m_c1 = c; }
int getC1Number() { return m_c1->returnNumber(); }
int returnNumber() { return 200; }
};
|
A number of solutions to a similar problem is found here;
http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.13
But, I can't get this to work for my situation since the classes are trying to get access to each other.
This is actually a simplification of my real problem. When creating a 'big' application like, for example, a game, one would create multiple classes like a spritemanager, soundmanager, field, camera etc. My idea was to create a 'superclass' which holds pointers of all classes. So for example, in the camera class I could call Super->Field->DoSomething(). The camera class has a pointer to the superclass, and the superclass has a pointer to the field class, but also to the camera class (which is exactly the situation I simplified above).
So, is there a solution to the simplified problem? If not or if it's too complicated, how else would I manage the above described situation? How do classes interact with each other while it's so hard to have them keep instances of each other?