View Single Post
Old Apr 30th, 2008, 4:22 PM   #3
Seif
Hobbyist Programmer
 
Seif's Avatar
 
Join Date: Jan 2006
Location: UK
Posts: 212
Rep Power: 3 Seif is on a distinguished road
Re: Cannot Function C++ Linked List

If the list is to be common among all player objects then try using a static data member.


c++ Syntax (Toggle Plain Text)
  1. class Player
  2. {
  3. public:
  4. player(int pid, string pName);
  5. int id;
  6. string name;
  7.  
  8. void printList();
  9. static std::list<Player*> player_list;
  10. };
  11.  
  12. // must be defined outside of class declaration
  13. std::list<Player*> Player::player_list;
  14.  
  15. Player::Player(int pid, string pName)
  16. {
  17. id = pid;
  18. name = pName;
  19. player_list.push_back(this);
  20. }
  21.  
  22. int main()
  23. {
  24. player *entity;
  25. for (int i = 0; i < 10; i++)
  26. entity = new player(i,"Seif");
  27.  
  28. entity->printList();
  29.  
  30. return 0;
  31. }

your printList() member will work fine with no modifications needed.

a brief description of whats going on:

only one copy of the static member player_list exists for all created player objects.

the static data member player_list is not considered part of the objects of type Player. They are externally linked and must therefore be defined outside the class scope.

for more info google for static members.

and on an unrelated note, try to make good use of the constructor as demonstrated above. It will make your life so much easier.

Last edited by Seif; Apr 30th, 2008 at 4:32 PM.
Seif is offline   Reply With Quote