Mutually recursive classes
Asked Answered
E

4

7

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_ */
Eisinger answered 4/8, 2010 at 23:24 Comment(2)
Do you have an objection to the -> operator?Marston
Actually I do. My way is simpler for me.Eisinger
F
7
  1. Forward-declare the classes (you could get away with forward-declaring only one of them, but for good form do both).
  2. 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();
  //...
}
Fatherland answered 4/8, 2010 at 23:42 Comment(2)
You forget to put the forward declaration, but this answer still has the code that is clearest to me.Eisinger
@drenami: Ack! Sorry, I had it in my test code, but goofed in the cut-and-paste. I'll fix it...Fatherland
S
4

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.

Sigismundo answered 4/8, 2010 at 23:30 Comment(0)
H
1

Predeclare one of the classes, for example Class2

#ifndef RECURSION_H_
#define RECURSION_H_
class Class2;
class Class1
{
   Class2* Class2_ptr;
   public:
   void Class1_method()
   {
      //...
      (*Class2_ptr).Class2_method();
      //...
   }
};

class Class2
{
     // ...
}  
Hypothecate answered 4/8, 2010 at 23:31 Comment(0)
H
1

Forward declare one of the classes (or both) on the top, eg.:

class Class2;
class Class1 { ... };

and define the methods after both of the classes are defined (that is, out-of-line):

class Class1
{
 ...
 void Class1_method(); // just declare
 ...
};

class Class2
{
 ...
};

// once definition of Class2 is known, we can define the method of Class1
void Class1::Class1_method()
{
      //...
      (*Class2_ptr).Class2_method();
      //...
}
Hispania answered 4/8, 2010 at 23:31 Comment(1)
What do you mean? How can you define the classes without defining the methods?Eisinger

© 2022 - 2024 — McMap. All rights reserved.