Programmatically getting the name of a derived class

steveo225 picture steveo225 · Jul 19, 2011 · Viewed 17.5k times · Source

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.

Answer

ysdx picture ysdx · Jul 19, 2011

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 :