How do I implement mutually recursive classes in C++? Something like:
/*
* Recursion.h
*
*/
#ifndef RECURSION_H_
#define RECURSION_H_
class Class1
{
Class2* Class2_ptr;
public:
void Class1_method()
{
//...
(*Class2_ptr).Class2_method();
//...
}
};
class Class2
{
Class1* Class1_ptr;
public:
void Class2_method()
{
//...
(*Class1_ptr).Class1_method();
//...
};
};
#endif /* RECURSION_H_ */
Predeclare one of the classes, for example
Class2
Forward declare one of the classes (or both) on the top, eg.:
and define the methods after both of the classes are defined (that is, out-of-line):
Use forward declaration.
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.