let's assume I have a super polymorphic base class Shape where many other shape classes are derived from it.
now if I have a vector of Shape pointers that contains a pointer to a list of different shape types like this:
vector<Shape*> p; // p contains pointer to many different shape objects
I know to have access to methods and members of each shape in vector p, I need to use dynamic_cast.
but what if I don't know what vector p actually contains at runtime? how can i safely find the type of an object contained in vector p at runtime?
i also know i can check if casting by dynamic_cast returns NULL or not for success. but does that mean to find the actual type of my shape object in vector p I have to do something like this:
if (dynamic_cast<Circle*> p[i] !=NULL){
// do stuff
}
else if (...) {
}
and repeat this pattern for all other shape types?
but this becomes cumbersome if I have 100 possible shapes. is there any better way to achieve this at rumtime?
ps- consider following scenario:
lets say I need to iterate through the Shape* vector and for example put all the circle objects in a separate vector and vector etc ... now i need to know the actual type of the objects. checking the return if typeid and dynamic_casts for many shapes is not practical.
dynamic_cast
is generally an anti-pattern. Use virtual methods instead. If you need to dynamically dispatch code based on the type of another object, give that object a virtualvisit()
method and use the visitor pattern instead. – cdhowie