C++: using typeinfo to test class inheritance

后端 未结 3 1841
一生所求
一生所求 2020-12-18 10:03

I have a pointer to a polymorphic type, p. I also have a type_info for a class somewhere in the same hierarchy, ti.

If I just

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-18 10:32

    Yes, you can use dynamic_cast<> for that purpose. If you try to cast to Base*, it performs a runtime check to see if your class really is derived from Base (or directly is a Base). In case of failure, dynamic_cast<> returns nullptr. Example :

    struct Base {
         virtual ~Base() {}
    };
    
    struct AnotherBase {
         virtual ~Base() {}
    };
    
    struct Derived : Base {};
    
    
    Base * basePtr = new Base();
    Base * derivedPtr = new Derived();
    AnotherBase * anotherBasePtr = new Base();
    
    // is derivedPtr a pointer to a class derived from AnotherBase ?
    AnotherBase* test2 = dynamic_cast(derivedPtr);    // test2 == nullptr
    
    // is basePtr a pointer to a class derived from Derived ?
    Derived * test3 = dynamic_cast(basePtr);    // test3 == nullptr
    

    Side nodes :

    • if dynamic_cast<> is used to convert pointers, it returns either nullptr or the converted pointer.

    • BUT when dynamic_cast<> is used to convert references it throws an exception in case of failure.

    • The runtime check of dynamic_cast<> is only possible for polymorphic types. If your Base doesn't contain any virtual function (= non polymorphic), it won't be possible to safely convert a Base* to a Derived*.

提交回复
热议问题