Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically getting the name of a derived class

Tags:

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.

like image 476
steveo225 Avatar asked Jul 19 '11 12:07

steveo225


People also ask

What is the name of the derived class?

A Derived class is also called a child class or subclass.

How do you identify a base class and a derived class?

1. A base class is an existing class from which the other classes are derived and inherit the methods and properties. A derived class is a class that is constructed from a base class or an existing class.

How do I get the ClassName in C++?

Finally to Get the class name you'd do the following: ClassName< MyClass >::name(); Edit2: Elaborating further you'd then need to put this "DefineClassName" macro in each class you make and define a "classname" function that would call the static template function. DefineClassName( MyClass );

Which keyword is used to identify a derived class?

The extends keyword in the Child class definition tells you it's a derived class.


2 Answers

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

like image 171
ysdx Avatar answered Sep 21 '22 11:09

ysdx


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; } 
like image 31
sharptooth Avatar answered Sep 22 '22 11:09

sharptooth