tags:

views:

167

answers:

2

I want to know the runtime type of a base class pointer, I know you can use dynamic_cast. is there any better way?

+3  A: 

The typeid operator does that. It gives you back a constant reference to a type_info object in constant time.

Also have a look at the Performance of typeid vs dynamic_cast<> tip over at devx.com.

Carl Seleborg
+7  A: 

dynamic_cast will only confirm your guess, and even that is not perfect. If C inherits from B which inherits from A, dynamic_cast<B*>((A*)&theC) will work. typeid will give you the actual type, but in a way that's not quite useful for anything. You can't create new objects of that same type, for instance.

So, the biq question that remains is what your real goal is. In proper OO design, you should never need to know about the unbounded set of types that can be derived from a base type.

MSalters
I must concur: polymorphism should diminish the need to check an object's type (unless you're writing debugging code...) +1
xtofl
Agreed. If you're using polymorphism properly, you should never care about the actual type of the object.
Rob K