Instanceof for objects in C ++ (not pointers)

If I have the following classes:

class Object { ... } class MyClass1: public Object { ... } class MyClass2: public Object { ... } 

and stack: std::stack<Object> statesObjects;

 MyClass1 c1; MyClass2 c2; statesObjects.push(c1); // okay statesObjects.push(c2); // okay 

How can I take them out and extract the element at the head of the stack (with top() ) without dynamic_cast , since I am not working with pointers here?

+6
source share
3 answers

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.

+8
source

You cannot bring them to your source classes, when you assign a subclass to an instance of a superclass, it gets sliced into an instance of the superclass. that is, the copies of c1 and c2 that are on the stack are now instances of Object , not their source classes

How can I call the child: virtual keyword not working method?

+2
source

Even if you seem to store the object of the derived class in your class, what will be stored will only be part of the Base class of the object. In short, you get Cropping objects .

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

Good reading:
What is object splitting?

+2
source

All Articles