Retrieving a c++ class name programmatically


Question

I was wondering if it is possible in C++ to retrieve the name of a class in string form without having to hardcode it into a variable or a getter. I'm aware that none of that information is actually used at runtime, therefor it is unavailable, but are there any macros that can be made to create this functionality?

Edit: May be helpful to note that I'm actually trying to retrieve the name of a derived class, and I'm using Visual C++ 2008 Express Edition.

1
54
3/23/2017 4:01:42 PM

Accepted Answer

You can use typeid:

#include <typeinfo>
cout << typeid(obj).name() << endl;

However, this is discouraged since the format isn't standardized and may differ between different compilers (or even different versions of the same compiler).

88
5/24/2017 9:14:32 AM

If you just want to check if it's certain class, then

typeid(obj) == typeid(CSubClass)

will always work regardless of the implementations.

Otherwise, a convenient way is to declare:

virtual const char* classname() { return "CMyClass";}

and implement per subclass.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon