Search code examples
c++dynamic-typing

Identifying a subclass given a pointer to its base class?


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.


Solution

  • 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.