Using typeid to get name of derived class

后端 未结 5 1680
孤城傲影
孤城傲影 2021-02-13 21:08

I\'m creating a resource manager that takes in classes derived from the class Resource. My problem is that typeid(..).name() returns the wrong name of the class.

5条回答
  •  有刺的猬
    2021-02-13 21:49

    Firstly, typeid can provide dynamic run-time type identification only for values of polymorphic class types. Your classes are not polymorphic. You need at least one virtual method in the base class in order to "activate" the dynamic behavior of typeid.

    Secondly, in order to use typeid for determining the dynamic type of polymorphic object, you have to apply it to the object itself, not to a pointer to the object (as in your code).

    Thirdly, the value returned by name() does not mean much and cannot be used for any practical purposes. Formally, name() can simply return an empty string every time. You have to use (and compare) the type_info objects themselves for run-time type identification.

提交回复
热议问题