Archived

This topic is now archived and is closed to further replies.

vector of children of pure virtual class

This topic is 5220 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hey guys, I''ve got a class called "Player"; it''s a pure virtual base class. It''s definition is something like: class Owner { public: virtual int takeTurn() = 0; } Then I have two classes which inherit from it, which are called "PlayerHuman" and "PlayerAi" respectively. I want to have a vector which consists of instances of PlayerHuman and PlayerAi (and any other classes I wish to derive from Player). I tried to make a vector of Player''s, but it wont allow me, saying that I''m trying to instantiate the pure virtual Player class. How do I get around this? I''m not _actually_ trying to instanciate the Player class. I''m not using any instances of the Player class in the vector, just instances of its children.

Share on other sites
you must use pointers to the virtual base class and call "new DerivedClass" to instantiate the classes.

Share on other sites
I''m guessing youre trying to do something like this?
vector<Owner*> players;players.push_back(new PlayerHuman(...));players.push_back(new PlayerAI(...));for(int i=0;i<players.size();i++)    players[i]->takeTurn()

Or did I get it wrong?

"On a long enough timeline the survival rate of everyone drops to zero"
- Fight Club

Share on other sites
Yeah, that''s the basic idea.

Share on other sites
Well this code works. I didn''t really get what your question was