Mutually recursive classes
Solution 1:
- Forward-declare the classes (you could get away with forward-declaring only one of them, but for good form do both).
- Forward-declare the methods (ditto).
class Class1;
class Class2;
class Class1
{
Class2* Class2_ptr;
public:
void Class1_method();
};
class Class2
{
Class1* Class1_ptr;
public:
void Class2_method();
};
void Class1::Class1_method()
{
//...
(*Class2_ptr).Class2_method();
//...
}
void Class2::Class2_method()
{
//...
(*Class1_ptr).Class1_method();
//...
}
Solution 2:
Use forward declaration.
class Class2;
class Class1
{
Class2* Class2_ptr;
};
class Class2
{
Class1* Class1_ptr;
}
Because the methods in Class1 will depend on the actual definition of Class2, method definitions must occur after the Class2 declaration, since you can't use methods from only a forward declaration.
On the other hand, this kind of tight coupling is usually indicative of bad design.