Sashank
Sashank

Reputation: 600

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?

Upvotes: 4

Views: 2418

Answers (4)

Harajyoti Das
Harajyoti Das

Reputation: 731

I agree with Dominic. I just like add two points here that the dynamic_cast overhead varies from compiler to compiler and if you don't have the option of re-designing your program then you have no options left,but to use dynamic_cast.(In case(not your case in question) where you are sure of the type then always prefer to use static_cast, it has very less overhead.)

Upvotes: 1

CJCombrink
CJCombrink

Reputation: 3950

I would suggest adding a field.

As others have mentioned, dynamic_cast<T>() can be used but you need to be careful and know when it will work and when not. For it to work you need RTTI (run-time type information) which is not always present/valid (such as when using libraries etc.)

I agree with @Dominic McDonnell:

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

PS: If you are using Qt then you can use qobject_cast<T>() since Qt adds this type of information to QObject type objects without the need for RTTI

Upvotes: 0

Nandu
Nandu

Reputation: 808

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.

Upvotes: 1

Dominique McDonnell
Dominique McDonnell

Reputation: 2520

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.

Upvotes: 4

Related Questions