Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knowing which derived class a base class pointer points to

Suppose I have an Animal class and two classes - Dog and Cat derive from it. It is perfectly legal to do this -

Dog d;
Cat c;
Animal* a1 = &c;
Animal* a2 = &d;

Now, given a1 and a2, can I know which derived class this pointer points to?

The only idea I have right now is to add one more member field inside Animal class and initializing it in constructors. Is this even a good practice?

like image 869
Sashank Avatar asked Oct 16 '25 18:10

Sashank


2 Answers

Yes it is legal, and yes that is one way of going back to the original type. You can also use dynamic_cast, but that has overhead. Generally the program stores it in the derived type and only refers to it with the base class when it doesn't matter.

I find if you are having to do something like dynamic_cast you have to reconsider the design of your program.

like image 172
Dominique McDonnell Avatar answered Oct 18 '25 11:10

Dominique McDonnell


you can use dynamic_cast to find out. Dynamic_cast uses run-time type check and will fail if it cannot convert accordingly.

ex: Derived* d = dynamic_cast<Derived*>(base)

Also if you use VStudio, you can use typeid(*a1).name. That'd give you the class name pointed to by a1 pointer.

like image 30
Nandu Avatar answered Oct 18 '25 13:10

Nandu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!