-
Interdependent Classes
I have a complicated problem that boils down to this:
2 classes that work together, need to have pointers to one another and complete access to all members and function.
the challenge lies in the fact that they cannot both be created at the same time. For example, a function in one class, uses the pointer to the other class to access a function or variable that doesn't technically exist yet. In case you're confused, here's a quick example of what i'm talking about:
Code:
class B; //a prototype so that class A knows class B exists;
class A
{
public:
B *classB; //pointer to class B
void fxnA();
void write();
};
void A::fxnA()
{
*classB->write();
}
void A::write()
{
cout<<"A"<<endl;
}
class B
{
public:
A *classA; //pointer to class A
void fxnB();
void write();
};
void B::fxnB()
{
*classA->write();
}
void B::write()
{
cout<<"B"<<endl;
}
When compiled the compiler throws "use of undefined type B" at:
*classB->write(); ( in fxnA() )
If the order of the classes is switched, fxnB() will throw the same error about A.
hopefully I'm just ignorant and forgetting something.
Help??
-
It should be working, but then again I'm getting rusty - been programming Flash.
One problem is it should be classB, not *classB, and classA, not *classA, you are using -> to show that its a pointer.
-
Move the definition of fxnA below the definition of class B.
-
Yeah, it should look like this:
Code:
class B;
class A
{
public:
B *classB;
void fxnA();
void write();
};
void A::write()
{
cout<<"A"<<endl;
}
class B
{
public:
A *classA;
void fxnB();
void write();
};
void B::fxnB()
{
classA->write();
}
void B::write()
{
cout<<"B"<<endl;
}
void A::fxnA()
{
classB->write();
}
-
In the case of interdependant classes its better to split it between header and source files. In the headers you put only the member variables, and prototype the member functions. In the source you define all the member functions. This will save you the above problem.