Finding the type of an object in C++


Question

I have a class A and another class that inherits from it, B. I am overriding a function that accepts an object of type A as a parameter, so I have to accept an A. However, I later call functions that only B has, so I want to return false and not proceed if the object passed is not of type B.

What is the best way to find out which type the object passed to my function is?

1
131
12/9/2008 5:06:51 AM

Accepted Answer

dynamic_cast should do the trick

TYPE& dynamic_cast<TYPE&> (object);
TYPE* dynamic_cast<TYPE*> (object);

The dynamic_cast keyword casts a datum from one pointer or reference type to another, performing a runtime check to ensure the validity of the cast.

If you attempt to cast to pointer to a type that is not a type of actual object, the result of the cast will be NULL. If you attempt to cast to reference to a type that is not a type of actual object, the cast will throw a bad_cast exception.

Make sure there is at least one virtual function in Base class to make dynamic_cast work.

146
6/7/2013 3:13:12 PM

Dynamic cast is the best for your description of problem, but I just want to add that you can find the class type with:

#include <typeinfo>

...
string s = typeid(YourClass).name()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon