I have a std::map containing pointers to a class called cEntity. These pointers are always passed as pointers, to avoid object slicing. However, I have a method called getItem(std::string s), that returns a pointer to the cEntity associated with the string s.
cEntity has a few classes derived from it, such as the player class - cPlayer. When a pointer to a cPlayer is returned, it is sliced - leaving only a cEntity class. Is this the language telling me to be a better programmer, or is there a solution?
Side note: If people from my previous posts see this, I did take your advice - and I am only using two managers now.
[source lang="cpp"]cEntity* cEntityManager::getItem(std::string s) { std::map<std::string, cEntity*>::iterator itr; itr = entityList.find(s); return itr->second;}[/source]
3 replies to this topic
Sponsor:
#2 Members - Reputation: 1566
Posted 04 October 2012 - 03:39 PM
If you know the type you should be able to use dynamic_cast on it, like this:
cPlayer *player = dynamic_cast<cPlayer*>(cEntityManager::getItem("Player"));
My Gamedev Journal: 2D Game Making, the Easy Way
---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)
---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)
#3 Members - Reputation: 178
Posted 04 October 2012 - 03:43 PM
Thanks, that is working nicely.
Out of curiosity, more than anything else, is there a way of designing my class heirachy so that the function can return any derived class pointer, and not slice it?
Out of curiosity, more than anything else, is there a way of designing my class heirachy so that the function can return any derived class pointer, and not slice it?
Edited by Silgen, 04 October 2012 - 03:55 PM.
#4 Crossbones+ - Reputation: 1179
Posted 04 October 2012 - 04:05 PM
It isn't sliced, but if you tell C++ to return you a cEntity pointer that is what the compiler will interprete it as, in memory however it is still a cPlayer object. And any virtual function you you call on this cEntity object will actually execute the cPlayer version if you overrode them in cPlayer.
Try this in a debugger, take the address of the cEntity that is returned when your request the player object and stick it in a memory window. You will see that the fields beyond the cEntity ones are set to values of your cPlayer object.
Try this in a debugger, take the address of the cEntity that is returned when your request the player object and stick it in a memory window. You will see that the fields beyond the cEntity ones are set to values of your cPlayer object.
Edited by NightCreature83, 04 October 2012 - 04:06 PM.






