c++typeid

Programmatically getting the name of a derived class


I am attempting to do something like:

class Base {
public:
   Base() {
      cout << typeid(*this).name() << endl;
   }
   ...
};

class Derived : public Base { ... }
class MoreDerived : public Derived { ... }

Derived d;
MoreDerived m;

Problem is, I always get Base printed to the screen, when I need to see Derived and MoreDerived. Is there a way to get typeid to work this way with derived classes? Or is there another approach besides typeid?

Note: I am adding functionality to an already coded suite, so I don't want to have to add a virtual method to the base class where the derived classes return this value themselves. Also, not worried about runtime overhead, this will be part of a debug compile switch.


Solution

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