You need to look at the typeid of the dereferenced pointer, not the pointer itself; I.e., typeid(*foo), not typeid(foo). Asking about the dereferenced pointer will get you the dynamic type; asking about the pointer itself will just get you the static type, as you observe.
Identifying a subclass given a pointer to its base class?
-
11-04-2022 - |
質問
Suppose that I have an abstract base class Parent and subclasses Child1 and Child2. If I have a function that takes a Parent*, is there a way (perhaps with RTTI?) to determine at runtime whether it's a Child1* or a Child2* that the function actually received?
My experience with RTTI here, so far, has been that when foo is a Parent*, typeid(foo) returns typeid(Parent*) regardless of the child class that foo's a member of.
解決
他のヒント
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 are using smart pointers, like std::shared_ptr
, you can check it like this:
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
}
Sure:
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 :'(
}
}
所属していません StackOverflow