Instanceof for objects in c++ (not pointers)

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.


You cannot pop them out to their original classes, when you assign a subclass to an instance of the superclass, it gets sliced into an instance of the superclass. i.e copies of c1 and c2 which are in the stack are now instances of Object and not their original classes

Similar to How can I make the method of child be called: virtual keyword not working?


Even if you seeminlgy store a derived class object in your class, what gets stored is only the Base class part of the object. In short You get Object Slicing.

To summarize, you cannot store derived class objects in this container. You will need to store a pointer to Base as the type of conainter and use dynamic polymorphism to acheive this.

Good Read:
What is object slicing?

Tags:

C++

Object

Stack