What is a common practice for the storage of a list of base class pointers each of which can describe a polymorphic derived class?
To elaborate and in the interest o
I would propose boost::shared_pointer
in an STL container. Then use dynamic_cast to downcast guarantee type correctness. If you want to provide helper functions to toss exceptions instead of returning NULL
, then follow Alex's suggestion and define a template helper function like:
template
T* downcast_to(U *inPtr) {
T* outPtr = dynamic_cast(inPtr);
if (outPtr == NULL) {
throw std::bad_cast("inappropriate cast");
}
return outPtr;
}
and use it like:
void some_function(Shape *shp) {
Circle *circ = downcast_to(shp);
// ...
}
Using a separate class like GenericShape
is just too strongly coupled with every class that descends from Shape
. I wonder if this would be considered a code smell or not...