Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instanceof for objects in c++ (not pointers)

Tags:

c++

stack

object

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 ?

like image 649
JAN Avatar asked Dec 19 '12 05:12

JAN


1 Answers

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.

like image 91
Cheers and hth. - Alf Avatar answered Oct 13 '22 02:10

Cheers and hth. - Alf