This is a question about how to implement some needs I have been having lately. I am sure there is a pattern or common solution for this and, even though I've come with one, I am eager to learn more.
Suppose I am working in a game in which all entities related to the game itself are derived from a class "Actor" (say "obstacle", "moving obstacle", "projectile" and "cannon"). In game, all those entities are stored in a std::vector<Actor *>
vector so they can be traversed.
Now, let's suppose each "Actor" can "do" something at each turn and let's give them a method "act". Obstacle::act would do little, Moving_obstacle::act and Projectile::act would move them around and "Cannon::act" would create a new projectile. It sort of makes sense to have a pure virtual function Actor::act so I can in turn do something like:
std::vector<Actor *>::iterator b=myvectorofactors.begin(), e=myvectorofactors.end();
while(b < e)
{
*b->act();
b++;
}
And have them all "acting". Well, so far so good... The thing is, Cannon::act could have a different prototype or return value (for example, to store a generated projectile and leter have it pushed into the vector) and this one "small" difference breaks it all.
Now, I know that from certain standpoint these method overloads are completely different functions each. I also know that one can always plan in advance and engineer through the problem with enough foresight... Or one can just manuever around the problem.
In this case at hand, I just used different unique identificators for each derived Actor class and used them to cast to the correspondent class and do the work around them. I am sure I will come around the same problem again and I am curious to know about some entry level solutions.
Thanks in advance for your time.