Search code examples
c++rttitypeid

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?


Solution

  • 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.