Alex Rivera | Logout

Identifying a subclass given a pointer to its base class?

Asked 2013-04-21T21:05:33.983
9

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.

Edit
Report

1 Answer

8

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.

answered 2013-04-21T21:12:37.010

Your Answer