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.
The actual reason is - a derived class has all information about a base class and also some extra bit of information. Now a pointer to a derived class will require more space and that is not sufficient in base class. So the a pointer to a derived class cannot point to it.
[19.4] Is it OK to convert a pointer from a derived class to its base class? Yes. (Note: this FAQ has to do with public inheritance; private and protected inheritance are different.)
Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.
// As base-class pointer cannot access the derived class variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With