Using typeid to get name of derived class

后端 未结 5 1751
孤城傲影
孤城傲影 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:53

    The typeid operator can only return the dynamic type of an expression, if that expression is a glvalue to an object of a polymorphic class.

    A class is polymorphic if it defines at least one virtual member function, directly or in one of its bases.

    Since your Resource class and the derived classes don't satisfy this requirement, the typeid operator can only access the static type.

    To solve that, and issues that you will run into as soon as you try to delete a pointer to such a resource, make the destructor virtual.

提交回复
热议问题