• Advertisement
Sign in to follow this  

Polymorphism Issues

This topic is 1937 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

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]

Share this post


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

Share this post


Link to post
Share on other sites
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? Edited by Silgen

Share this post


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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement