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

不羁的心 提交于 2019-12-18 12:18:07

问题


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.

Base* b = new Derived():

typeid(b).name(); // i want this to tell me that this is actually derived not base object

is there any way other than manual implementation of string field or such and virtual get function?

PS: I talking about compiler-independent solution


回答1:


make sure the base class has at least one virtual method, include <typeinfo> 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).”




回答2:


If all you want to do is find if b actually points to Derived, just use dynamic_cast():

if (dynamic_cast<Derived*>(b)) { ... }

dynamic_cast returns a null pointer if the actual runtime type of the object pointed to by b is not Derived (or a class derived from Derived). Unlike the name() member of std::type_info, this is compiler-invariant.

Note that this only works if Base has at least one virtual member functions. Which it should anyway, since you're manipulating types derived from it through a base pointer, so it should have a virtual destructor.



来源:https://stackoverflow.com/questions/15898121/how-to-determine-actual-object-type-at-runtime-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!