Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 380
ExOttoyuhr Avatar asked Apr 21 '13 21:04

ExOttoyuhr


People also ask

Why a pointer to a subclass may not point to its base class?

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.

Can you convert a pointer from a derived class to its base class?

[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.)

What can hold the address of a pointer to the base class A base class object only a B derived class object?

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.

Can a base class pointer call methods in the derived class?

// As base-class pointer cannot access the derived class variable.


1 Answers

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.

like image 51
Ernest Friedman-Hill Avatar answered Sep 24 '22 00:09

Ernest Friedman-Hill