Setting a pointer to another object in the class

Generally speaking, how would I set a pointer to another object in the same class? For example, say I was building a class called "Team." After I create objects (team members), I want to have a pointer data field which will allow me to point to another team member ("partner"). Setting a team member as a partner should also set up a pointer from that person to the original member I set the partner for. I.E. if I create a team member Harry and point to another team member Ron as his partner, Ron should "point" to Harry as his partner, too.

Am I on the right track? How would I construct these objects?

1
2
3
4
5
6
7
8
class Team
{
public:

bool practiced;
Team partner;
};
If you want to set up a pointer to another team instance, you need to declare the pointer as such.
1
2
3
4
5
6
7
class Team
{
public:

  bool practiced;
  Team * partner;
};


As far as creating a pairing between two team instances, I'd probably create a static function that takes two team instances:
1
2
3
4
5
6
7
8
class Team
{
public: 
  static CreatePairing (Team * t1, Team *t2)
  {  t1->partner = t2;
      t2->partner = t1;
  }
};





Last edited on
Thanks, you were a great help. I'm having trouble with the createPairing function, though. How should I call the function in the main function? It is giving me an error when I try to compile.

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
class Team
{
	public:
	
	Team();
	Team(bool prac, Team *part);
	void createPairing (Team *t1, Team *t2);

	private:
	
	bool practiced;
	Team *partner;
};


Team::Team()
{
	practiced = false;
	partner = 0;
}

Team::Team(bool prac, Team *part)
{
	practiced = prac;
	partner = part;
}

void Team::createPairing (Team *t1, Team *t2)
{
	t1->partner = t2;
	t2->partner = t1;
}

int main()
{
	Team Harry;
	Team Ron;
	createPairing(Harry, Ron);
	
	return 0;
}
You're missing the static keyword on line 7.

static means that it doesn't refer to a specific instance. Both instances are passed as arguments to createpairing.
Topic archived. No new replies allowed.