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.
You are using private inheritance, so it is not possible to use
dynamic_cast
to determine whether one class is derived from another. However, you can usestd::is_base_of
, which will tell you this at compile time:What you need is
dynamic_cast
. In its pointer form, it will return a null pointer if the cast cannot be performed:Example: