//class1.h
public class class1
{
class2 getClass2(int index);
}
//class2.h
public class class2
{
class1 getClass1(int index);
}
C++ Class Recursion
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:
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?
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement