for (auto it = objects.begin(); it != objects.end(); it++)
{
if ((*it)->objectType == GameObject::tower)
{
Tower* tower = static_cast<Tower*>(*it);
tower->Update(objects);
}
elseif ((*it)->objectType == GameObject::enemy)
{
Enemy* enemy = static_cast<Enemy*.(*it);
enemy->Update();
}
}
example 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
for (auto it = objects.begin(); it != objects.end(); it++)
{
Tower* tower = dynamic_cast<Tower*>(*it);
Enemy* enemy = dynamic_cast<Tower*>(*it);
if (tower)
{
tower->Update(objects);
}
elseif (enemy)
{
enemy->Update();
}
}
I think I can (hopefully) guess example one is faster, which brings me to the next question: is this the best way to cycle though update functions with all game objects that share a base class [GameObject}? seems ok to me, just want some input.
Additionally those snippets might do a different things if Tower class has child classes which sets own objectType.
Usually having to resort to casts means that you made a desing error somewhere. You should really reconsider it and maybe make Update() a part of common class interface.
You can either pass objects to it (which would mean passing objects to Enemy's Update function, but it can just ignore it) or don't and store reference to it inside Tower object (will only works if you need to pass same container on all iterations) so it will not need additional parameter in Update function