Check if an object type is inherited from a specific class

In C ++, how can I check if an object type 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 request is executed on all elements of the Form list. All objects whose type is inherited from Moveable can be moved and need to be processed so that other objects are not needed.

+6
source share
3 answers

You need 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 } 
+21
source

You are using personal inheritance, so you cannot use dynamic_cast to determine if one class is derived from another. However, you can use std::is_base_of , which will tell you this at compile time:

 #include <type_traits> class Foo {}; class Bar : Foo {}; class Baz {}; int main() { std::cout << std::boolalpha; std::cout << std::is_base_of<Foo, Bar>::value << '\n'; // true std::cout << std::is_base_of<Bar,Foo>::value << '\n'; // false std::cout << std::is_base_of<Bar,Baz>::value << '\n'; // false } 
+8
source

Runtime Information (RTTI) is a mechanism that allows the type of object to be determined at runtime. Added RTTI to C ++, since many class library vendors have been implementing this functionality on their own.

Example:

 //moveable will be non-NULL only if dyanmic_cast succeeds Moveable* moveable = dynamic_cast<Moveable*>(&John); if(moveable) //Type of the object is Moveable { } 
+4
source

Source: https://habr.com/ru/post/928072/


All Articles