简体   繁体   中英

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.

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:

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;
}

Another option is to provide a virtual toName() function

struct Object{
  virtual std::string toName() const = 0;
}
struct Base: Object{
  std::string toName()const{ return "Base"; }
}
struct Derived: Base, Object{
  std::string toName()const{ return "Derived"; }

This might get tedious since you need to manually create each toName function. But the advantage it gives you is to provide your own custom name.

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