• Advertisement

Archived

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

std::vector iterator class casting problem

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

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!

Share this post


Link to post
Share on other sites
Advertisement
Ooopps. Thanks for reminding me to add that Asteroid is derived from Entity..


  
struct Entity {
DWORD dwType;
};

struct Asteroid : public Entity {

};


thanks!

Share this post


Link to post
Share on other sites
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; 

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

  • Advertisement