Public Group

2 classes with pointers to each other: C++

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

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 on other sites
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.hclass Class2; // Declare that a class named Class2 existsclass Class1{    Class2 *class2;};

// Class2.hclass Class1; // Declare that a class named Class1 existsclass 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.

Try this:

class A;
class B;

class A {

B *b;
};

class B {

A *a;
};

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

1. 1
2. 2
Rutin
19
3. 3
khawk
15
4. 4
A4L
14
5. 5

• 9
• 13
• 26
• 10
• 11
• Forum Statistics

• Total Topics
633744
• Total Posts
3013662
×