Skip to main content
GameDev.net gamedev.net
🔒 Locked

std::vector iterator class casting problem

Started by Iolo Jan 22, 2003 at 9:17 AM 4 replies 1k views
Original Post
Iolo
Iolo
Hi everyone, I''m trying to use a std::vector object of some base class objects, then recast them depending upon their type... ie
  
1. for(std::vector<Entity>::iterator i = m_vecEntities.begin(); 
2.   i != m_vecEntities.end(); ++i){
3.
4.   Entity &ThisClass = *i;
5.
6.   //now do a switch depending upon the entity type

7.   switch(ThisClass.dwType){
8.     case ASTEROID_ENTITY:
9.       /****************************
10.        ** THIS IS THE LINE THAT BREAKS **
11.        ********************************/
12.     Asteroid oRock = (Asteroid)ThisClass; //????

  
as you can tell, once I''ve determined which type of Entity object I''m dealing with, I want to re-cast it to the proper subclass of Entity to access the member variables/methods I need.. I know I''m doing the recasting wrong (line 12), but am I also doing the original Entity object grab wrong? (line 4)?? thanks for any help!
Qw3r7yU10p!
Qw3r7yU10p!
The objects are all of class Entity - how can it possibly also be an Asteroid?
Iolo
Iolo
Ooopps. Thanks for reminding me to add that Asteroid is derived from Entity..


  
struct Entity {
DWORD dwType;
};

struct Asteroid : public Entity {

};


thanks!
null_pointer
null_pointer
You are storying Entity objects by value, which means that inserting an Asteroid into that container will just insert the Entity part of the object. If you wish to store objects of types derived from Entity, you must create a container of pointers to Entity objects, i.e.:
vector <Entity*> m_vecEntities; 
null_pointer
null_pointer
Oh, and if you allocate the objects that you insert with operator new, you must also remember to delete them. A container of pointers will only manage the memory for the pointers themselves and not the objects to which the pointers point.
Iolo
Iolo
Thanks null_pointer, I''ll give that a shot!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.