C++ Class Recursion

Started by
3 comments, last by Fruny 18 years, 7 months ago
I'm trying to make two different C++ classes reference each other, but can't figure out how. Basically, I want the method of one class to return an instace of the other class, and that class to be able to return an instance of the first, like this:

//class1.h
public class class1
{
  class2 getClass2(int index);
} 

//class2.h
public class class2
{
  class1 getClass1(int index);
} 

I'm using DevC++ with MingW for this project. Any ideas on how to get this to work, without having to do something messy like have one or the other return a void?
Advertisement
Well, you can't do that, unfortunately. Not quite. You CAN, however, have them return pointers or references to each other. Given that you're using Java-like syntax there (which uses pointer-like types for referring to objects), it's likely that that's what you want anyway. Here is the article that will r0x0r your b0x0r.
////////////////////////////class1.hclass class2;class class1{  class2 getClass2(int index);}; ////////////////////////////class2.hclass class 1;class class2{  class1 getClass1(int index);};


Must-read article.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Thanks man, consider my b0x0rz r0x0r3d ^^. I actually meant them to be pointers but forgot the "*"'s. Anyways that article had the perfect answer, I never knew you could prototype a class pointer. Very cool.
Quote:Original post by Oranda
Thanks man, consider my b0x0rz r0x0r3d ^^. I actually meant them to be pointers but forgot the "*"'s. Anyways that article had the perfect answer, I never knew you could prototype a class pointer. Very cool.


An incomplete type (which is what the class declaration results in) can be used to define a pointer, a reference, or to declare a function taking or returning that type. Of course, actually creating or using a variable requires a complete type.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement