Eirik Skarbø
Eirik Skarbø

Reputation: 21

How to share data between distant classes?

I'm a c++ newbie, and I currently having trouble retrieving data from two very distant classes. Here is the hierarchy:

class Sports contains a List of sport objects. A sport object contains a division List with division objects, and the division objects contains an array called teams with pointers pointing to team objects.

*List in this context is an external class (linked list) which my teacher has made and is mandatory to use, none of these classes are derived from each other.

I need to access data members from the team class too the Sports class, and because they are very distant I do not know how to do this. Any suggestions are greatly appreciated.

Upvotes: 2

Views: 103

Answers (2)

Potato
Potato

Reputation: 638

Well, I can can three possible solutions:

1) you could make you team fields public 2) create getter/inspector methods for desired fields 3) or use friend. http://en.cppreference.com/w/cpp/language/friend

Which one you think is best is up to you

Upvotes: 2

Serge
Serge

Reputation: 12384

so, conceptually you have something like the following

x->[sport0][sport1]...
   |
   +-> [division0][division1]...
           |
           +->[team0][team1]...

a couple of things you need to clarify: can one team be in multiple divisions? Can multiple sports have the same divisions?

Usually in situations like this you have few possibilities. From the team you can traverse the whole tree struct from x (if it is available) and remember sports ans divisions which you hit on the way. You stop when you find your team(s).

The other common way is to create backwards pointers from the teams to the divisions and from divisions to the sports. This way you can very quickly get info which you need.

x->[sport0][sport1]...
   |   ^----+----------+---
   |        |          |
   +-> [division0][division1]...
           |  ^-+------+----
           |    |      |
           +->[team0][team1]...

You can create the back pointers on while you create a list, or when you do a full traversal.

You can come up with other ways as well.

Upvotes: 1

Related Questions