Programmatically getting the name of a derived class

In the constructor Base(), the object is still a "Base" instance. It will become a Derived instance after the Base() constructor. Try to do it after the construction and it will work.

See for example :

  • Avoiding virtual methods in constructor

  • Never Call Virtual Functions during Construction or Destruction


You can't do that from within a constructor (or destructor) - neither with typeid nor with a virtual method. The reason is while you're in a constructor the vtable pointer is set to the base class being constructed, so the object is of base class and no amount of polymorphism will help at that point.

You have to execute that code after the most derived class has been constructed. One option would be to use a factory function:

template<class T>
T* CreateInstance()
{
    T* object = new T();
    cout << typeid(*object).name() << endl;
    return object;
}

Tags:

C++

Typeid