The short answer is that somehow with your stack you cannot pull elements as elements of a type of a derived class. By putting them on the stack, you chopped them into the stack element class. That is, only part of the base class was copied onto the stack.
However, you can have a stack of pointers, and then you can use dynamic_cast provided that the statically known class has at least one function of the virtual member or, as the standard says, provided that the statically known class is polymorphic .
However, on the third and exciting hand, instead of a Java-like downcast, a virtual function is used in a common base class. Often it works just to have such a function. For more complex scenarios, you may need to use the google it template, but the main idea is that virtual functions are a “safe” language that supports the type of safe way to achieve the effect of downcasts.
source share