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