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.
A Derived class is also called a child class or subclass.
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.
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 );
The extends keyword in the Child class definition tells you it's 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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With