How to determine actual object type at runtime in C++;

前端 未结 2 861
耶瑟儿~
耶瑟儿~ 2020-12-30 03:51

Lets say we have a class hierarchy. At the bottom we have Base and at the top Derived. How to determine object class even if it is converted to base class pointer.



        
2条回答
  •  无人及你
    2020-12-30 04:16

    make sure the base class has at least one virtual method, include and use your current code just with an additional dereferencing, typeid(*b).name().


    in passing, note that a typeid call is the one place in C++ where you can dereference a nullpointer with well-defined behavior, which implies that it can throw an exception:

    C++11 §5.2.8/2:
    “If the glvalue expression is obtained by applying the unary * operator to a pointer and the pointer is a null pointer value (4.10), the typeid expression throws the std::bad_typeid exception (18.7.3).”

提交回复
热议问题