Subclass identification with a pointer to its base class?

Suppose I have an abstract base class Parent and subclasses Child1 and Child2. If I have a function that accepts the parent element *, is there a way (possibly with RTTI?) To determine at runtime whether it is Child1 * or Child2 *, what is the actual function received?

My experience with RTTI here so far has been that when foo is Parent *, typeid (foo) returns typeid (Parent *) regardless of the child class that foo is a member of.

+7
source share
3 answers

You need to look at the typeid of the dereferenced pointer, not the pointer; Ie, typeid (* foo), not typeid (foo). If you ask about a dereferenced pointer, you will get a dynamic type; when asking about the pointer itself, you will only get a static type, as you noticed.

+5
source

You can use std::dynamic_cast for this.

 Parent* ptr = new Child1(); if(dynamic_cast<Child1*>(ptr) != nullptr) { // ptr is object of Child1 class } else if(dynamic_cast<Child2*>(ptr) != nullptr) { // ptr is object of Child2 class } 

Also, if you use smart pointers like std::shared_ptr , you can check this as follows:

 std::shared_ptr<Parent> ptr(new Child1()); if(std::dynamic_pointer_cast<Child1>(ptr) != nullptr) { // ptr is object of Child1 class } else if(std::dynamic_pointer_cast<Child2>(ptr) != nullptr) { // ptr is object of Child2 class } 
+5
source

Of course:

 BaseClass *bptr = // whatever, pointer to base class SubclassOne *safe_ptr_one = dynamic_cast<SubclassOne *>(bptr); if (safe_ptr_one != nullptr) { // Instance of SubclassOne } else { // not an instance of SubclassOne, try the other one SubclassTwo *safe_ptr_two = dynamic_cast<SubclassTwo *>(bptr); if (safe_ptr_two != nullptr) { // Instance of SubclassTwo } else { // it wasn't either one :'( } } 
+2
source

All Articles