Jump to content
  • Advertisement
Sign in to follow this  
tonywatts

2 classes with pointers to each other: C++

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all. So, I have two separate classes, each one containing a pointer to the other. This seems to be causing some problems, presumably because whichever one gets declared first doesn't know what I'm talking about when in class1 I make the private variable
class2* pointername
Is there any way around this? Cheers Tony

Share this post


Link to post
Share on other sites
Advertisement
Declare each class in the other class's header file without including the full declaration. Then, include the appropriate headers in the .cpp files.


// Class1.h
class Class2; // Declare that a class named Class2 exists

class Class1
{
Class2 *class2;
};




// Class2.h
class Class1; // Declare that a class named Class1 exists

class Class2
{
Class1 *class1;
};




// Class1.cpp
#include "Class1.h"
#include "Class2.h"




// Class2.cpp
#include "Class1.h"
#include "Class2.h"




The drawback is that you cannot use the pointers in inline functions in the header file, as the full class declaration is unknown.

Share this post


Link to post
Share on other sites
Quote:
Original post by pi_equals_3
The drawback is that you cannot use the pointers in inline functions in the header file, as the full class declaration is unknown.


It's possible to have cyclical dependencies and put inline functions in the headers; it just requires a little massaging of the common header file format.

class1.h:

class class2;

class class1 {
// stuff
};

#include "class2.h"

// inline functions



class2.h:

class class1;

class class2 {
// stuff
};

#include "class1.h"

// inline functions

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!