Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 398
danijar Avatar asked Oct 18 '12 20:10

danijar


People also ask

How do you check if an object belongs to a certain class in C++?

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.

How do I check if an object is an instance of a given class or of a subclass of it?

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).

Which operator is used to check if the object of a class is inheriting a property from another class?

The instanceof operator allows to check whether an object belongs to a certain class. It also takes inheritance into account.


1 Answers

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
}
like image 164
K-ballo Avatar answered Oct 13 '22 00:10

K-ballo