Objects with pointers to each other

Hello. I'm a beginner at C++ and have had a lot of fun learning the basics of the language. However, I've run into a problem that I can't seem to solve. I'm trying to make two objects each with variables that are pointers to each other but I can't seem to find a way to do it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Player{
	Bag* myBag;
public:
	Player(){
		Player* me = this;
		myBag = new Bag(me);
	}
}

class Bag{
	Player* myPlayer;
public:
	Bag(Player* thePlayer){
		myPlayer = thePlayer;
	}
}

This obviously doesn't work but I can't find a way to declare Bag before Player or anything else. Thanks in advance for any help.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>

class beta; // declare the existence of a class named beta so that I can define alpha to have
         //   a pointer to such an object

class alpha{
public:
int a;
beta* p_some_beta_object;};

class beta{
public:
int b;
alpha* p_some_alpha_object;};

int main()
{

alpha an_alpha_object;
beta a_beta_object;

an_alpha_object.p_some_beta_object = &a_beta_object;
a_beta_object.p_some_alpha_object = &an_alpha_object;

an_alpha_object.a=1;
a_beta_object.b=2;

std::cout << " an_alpha_object.a = " <<  an_alpha_object.a << std::endl;
std::cout << " a_beta_object.b = " <<  a_beta_object.b  << std::endl;

// Change the beta object through the alpha object
an_alpha_object.p_some_beta_object->b= 17;

// Change the alpha object through the beta object
a_beta_object.p_some_alpha_object->a = 56;

std::cout << " an_alpha_object.a = " <<  an_alpha_object.a << std::endl;
std::cout << " a_beta_object.b = " <<  a_beta_object.b  << std::endl;

return 0;
}
Last edited on
Thanks. That's just what I needed.
Topic archived. No new replies allowed.