Polymorphism Issues

Started by
2 comments, last by NightCreature83 11 years, 6 months ago
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]
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"));

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)

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?
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.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

This topic is closed to new replies.

Advertisement