# C++ Class Recursion

This topic is 4873 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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?

##### Share on other sites
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.

##### Share on other sites
////////////////////////////class1.hclass class2;class class1{  class2 getClass2(int index);}; ////////////////////////////class2.hclass class 1;class class2{  class1 getClass1(int index);};

##### Share on other sites
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.

##### Share on other sites
Quote:
 Original post by OrandaThanks 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.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 15
• 14
• 46
• 22
• 27
• ### Forum Statistics

• Total Topics
634046
• Total Posts
3015224
×