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.
C++ has no direct method to check one object is an instance of some class type or not. In Java, we can get this kind of facility. In C++11, we can find one item called is_base_of<Base, T>. This will check if the given class is a base of the given object or not.
The isinstance() method checks whether an object is an instance of a class whereas issubclass() method asks whether one class is a subclass of another class (or other classes).
The instanceof operator allows to check whether an object belongs to a certain class. It also takes inheritance into account.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With