Alex Rivera | Logout

Check if the Type of an Object is inherited from a specific Class

Asked 2012-10-18T20:35:40.640
20

In C++, how can I check if the type of an object is inherited from a specific class?

class Form { };
class Moveable : public Form { };
class Animatable : public Form { };

class Character : public Moveable, public Animatable { };
Character John;

if(John is moveable)
// ...

In my implementation the if query is executed over all elements of a Form list. All objects which type is inherited from Moveable can move and need processing for that which other objects don't need.

Edit
Report

1 Answer

31

What you need is dynamic_cast. In its pointer form, it will return a null pointer if the cast cannot be performed:

if( Moveable* moveable_john = dynamic_cast< Moveable* >( &John ) )
{
    // do something with moveable_john
}
answered 2012-10-18T20:40:43.490

Your Answer