If I have the following classes :
class Object { ... }
class MyClass1: public Object { ... }
class MyClass2: public Object { ... }
and a stack : std::stack<Object> statesObjects;
MyClass1 c1;
MyClass2 c2;
statesObjects.push(c1); // okay
statesObjects.push(c2); // okay
How can I pop them out and retrieve the element at the head of the stack (with top()
) without dynamic_cast
, since I don't work with pointers here ?
The short answer is, that with your stack as-is you can't pop out the elements as derived-class type elements. By putting them into the stack you have sliced them to the element class of the stack. That is, only that base class part has been copied into the stack.
You can have a stack of pointers, however, and then you can use dynamic_cast
provided that the statically known class has at least one virtual
member function, or as the standard says, provided that the statically known class is polymorphic.
On the third and gripping hand, however, instead of the Java-like downcast use a virtual function in the common base class. Often it works to just directly have such a function. For more complicated scenarios you may have to use the visitor pattern (google it), but basically, the idea is that virtual functions are the “safe” language-supported type safe way to achieve the effect of downcasts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With