Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get child's class name from parent

Tags:

c++

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?

like image 528
Humberd Avatar asked Sep 11 '25 17:09

Humberd


2 Answers

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]

like image 98
Angew is no longer proud of SO Avatar answered Sep 13 '25 06:09

Angew is no longer proud of SO


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.

like image 38
Hatted Rooster Avatar answered Sep 13 '25 07:09

Hatted Rooster