Given a base class of gameObject
and a derived class of animatedGameObject
, I thought it may be good to store all of their instances in an std::vector
. If the vector GameObjects
is declared to be the base type of gameObject*
, derived object instances require casting.
Example:
vector<gameObject*> GameObjects;
gameObject A* = new gameObject( ...init... );
animatedGameObject B* = new animatedGameObject( ...init... );
GameObjects.push_back(A);
GameObjects.push_back(B);
// to access the animatedGameObject functions:
static_cast<animatedGameObject*>(GameObjects[1])->functionUniqueToAnimated();
Being afraid as per usual, I turned to Scott Meyers (Effective C++, 3rd Edition), who writes on the subject:
Many programmers believe that casts do nothing but tell compilers to treat one type as another, but this is mistaken. Type conversions of any kind (either explicit via casts or implicit by compilers) often lead to code that is executed at runtime.
I've read through his Item 27: Minimize Casting twice, yet given my inexperience with this, I am struggling with my inability to answer a simple question "IS THIS A DUMB THING TO DO?"
I should mention that there are several reasons why it is a dumb thing to do that have nothing to do with invoking static_cast
. The questions, in order of importance, are:
- Am I not seeing some possible risks with the use of
static_cast
in my example above? - Are there better data structures than the
std::vector
for such approaches? (only if there's one that is obvious, I'm not asking you to do my research for me.)
This is my first time asking a question here, so apologies in advance, where necessary.