Ahmed
Ahmed

Reputation: 7238

what is the best way to check the type of base class pointer?

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

Upvotes: 1

Views: 278

Answers (2)

MSalters
MSalters

Reputation: 179789

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.

Upvotes: 7

Carl Seleborg
Carl Seleborg

Reputation: 13295

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.

Upvotes: 3

Related Questions