Is there some way to allocate memory depending on the type of pointer passed?
Here is my problem: I have a ‘bouncyball’ and ‘hero’ class both inheriting from ‘Actor’. To add a bouncyball, I call:
_actors.push_back(new Bouncyball());
For a hero, it would be:
_actors.push_back(new Hero());
Since _actors is a vector of Actor pointers, it works because of polymorphism. But I want to write a generic method to add new actors to my scene:
unsigned Scene::addActor(Actor * actor){
this->_actors.push_back(new [something]);
}
Because the parameter can be any derivative of Actor, I don’t know what to allocate memory for… I can work around this with a case statement, but what if I derive other Actors later on?
What is wrong with this:
Isn’t it
actorwhich you want to add to_actors?And you can call
addActor()as:Make sure that you declare the destructor of
Actorasvirtual, as most likely you would want to delete derived class objects through the pointer of base type (which isActor).