I want to get child's class name from parent pointer.
class Parent{
}
class Child: Parent {
}
Parent* parent = new Child;
cout << typeid(parent).name(); //it prints "Parent", but I want to print "Child"
How to do it?
First off, the class has to be polymorphic, i.e. have at least one virtual function. Normally, you'd make this the destructor, because base classes without virtual destructors are a recipe for trouble.
Then, you'll need to query the type of the object and not of the pointer to it. Put together:
class Parent
{
public:
virtual ~Parent() = default;
};
class Child : public Parent
{
};
Parent *parent = new Child;
cout << typeid(*parent).name();
[Live example]
As cppreference explains, parent
needs to be a polymorphic object.
In other words, adding at least 1 virtual
method to your Parent
will get you your desired result.
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