How to identify the type of a class at runtime

Started by
5 comments, last by JohnsonGPS 16 years, 11 months ago
I have an impression there is a C++ function call to identify the type of a class, for example, whether it is derived from a certain base class or not. I could not remeber the name of that function. Anybody can help? Thanks. Johnson
Advertisement
Not quite a function, but dynamic_cast seems to be what you are looking for. Beware though, there are usually far more elegant ways to handle what you are trying to do. After all, if different objects derive from the same base they should act the same to client code. If they do not, then they don't truly inherit from such a base (although common functionality can still be retained through aggregation or private inheritance). See here.
Well if the pointer is to a generic base class and you want a derived type you can attempt to dynamic_cast to the derived type.

Or you can look into using type_info to check an object type.

Usually though if you are finding yourself having to do this a bunch it might be a sign that the design may need to be revisited.
The one I could not remember is actually typeid operator. However, I still have an impression there is something else that can do almost the same thing, whose name is similar to IsClass() or IsObject(). Anybody has a clue?

Thanks.

Johnson
Type traits implementations can do this (via template metaprogramming). However, they're not (yet) standard. The only "natural" ways of doing it are via typeid() and the type_info object, or via dynamic_cast.

What are you trying to do, really? As others have said, there are usually more elegant methods.
Maybe you're thinking aboust boost::is_base_of? Although that's compile-time, nor run-time.

You can use dynamic_cast to write such a function(assuming you deal with polymorphic classes and RTTI):

template <class KLASS,class T> bool is_instance(T* instance)
{
return (dynamic_cast<KLASS*>(instance)!=NULL);
}

You can know check if "my_instance" is of type "Foo" by doing:

is_instance<Foo>(my_instance);

Using something like that though in C++ means most times that there is something in the design that could be improved.
Thank you all for the information. I just want to brush up my knowledge.

Johnson

This topic is closed to new replies.

Advertisement