Access address of class objects inside std::List.

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
#include <iostream>
#include <list>

using namespace std;
list<void*> playerlist;

class player {

protected:
    void* id;

public:
    player (){id=this,playerlist.push_back(id);} //pushing my id to list;

    const void* getid() {return id;}
};


int main()
{
    player * firstplayer = new player(); //creating new player object.

    list<void*>::iterator it = playerlist.begin();

    while(it != playerlist.end()){
         cout <<"Object id is = " << **it.getid() << endl; //error here!
         it++;
    }

    delete firstplayer;
    return 0;
}


Thnx for help.
You don't want to use void pointers to your class.
You lose all strong typing protections C++ provides.

Line 13: Why does player have a void pointer to itself? You can always get the address of the current instance by using the this pointer.

What you're missing is the concept of a forward class declaration. Line 6 below says that the declaration of player will come later. Once you've declared that a class is forward, you use a pointer to that class.

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
#include <iostream>
#include <list>

using namespace std;

class player;               //  Forward declaration
list<player *> playerlist;      

class player 
{   
public:
    player ()
    {   playerlist.push_back(this);     //  Pushing this instance to list
    }   
};
                              
int main()
{   player * firstplayer = new player(); //creating new player object.

    list<player *>::iterator it = playerlist.begin();
    while(it != playerlist.end())
    {   cout <<"Object id is = " << *it << endl; 
         it++;
    }
    delete firstplayer;
    return 0;
}



Last edited on
no need to use dynamic allocation
Thank you AbstractionAnon.

Topic archived. No new replies allowed.