简体   繁体   中英

Strange behavior of run-time type information

I've two class Base and Derived as this:

class Base
{
public:
};

class Derived : public Base
{
public:
};

and main function:

int main()
{
    Base* ptr = new Derived;

    std::cout << typeid(*ptr).name() << endl;

    delete ptr;

    system("pause");
}

Program outputs shows class Base where I expected it will show class Derived . But when I've added a virtual method in the Base class, now outputs shows class Derived !

Why RTTI needs at least one virtual method?

Because the language specification says so. RTTI only works on polymorphic types; that is, types with virtual functions. For other types, typeid returns the type info for the static type of its argument.

If you're asking for a rationale for this: it has a run-time cost (typically, a pointer in each object to the per-class metadata, which supports both virtual dispatch and RTTI), and it would be a shame if you had to pay that price for all types, whether or not you want to use RTTI on them.

Too long for a comment.

1) Refers to a std::type_info object representing the type type. If type is a reference type, the result refers to the referenced type.

2) Examines the expression expression

a) If expression is a glvalue expression that identifies an object of a polymorphic type (that is, a class that declares or inherits at least one virtual function), the typeid expression evaluates the expression and then refers to the std::type_info object that represents the dynamic type of the expression . If the result of the evaluated expression is a null pointer, an exception of type std::bad_typeid or a type derived from std::bad_typeid is thrown.

b) If expression is not a glvalue expression of polymorphic type, typeid does not evaluate the expression, and the std::type_info object it identifies represents the static type of the expression . Lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversions are not performed.

Thus the behavior is expected, since in one case the class is polymorphic, and in the other it's not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM