tags:

views:

3423

answers:

1

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? Thanks.

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.

+16  A: 

You can use RTTI:

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

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

Konrad Rudolph
Interesting, I didn't know about this. It seems to work pretty well. It gives me a bit more text than I wanted in the response, but it seems to work pretty well. Thanks!
Morgan
@Konrad - Will this work of there are no virtual methods in the class? I though RTTI doesn't work in this case. I guess as long as you have a virtual destructor you will be okay.
LeopardSkinPillBoxHat
@LeopardSkinPillBoxHat: Yes, it will work (see §5.2.8/3 and 4). It’s a common misconception that `typeid` will only work with polymorphic types, probably stemming from the similarity to RTTI features. – In fact, using `typeid` on static types does not need, and does not use, RTTI. The operator is evaluated at compile time and the result is compiled in (strictly speaking, that’s an implementation detail but it’s the only sane implementation).
Konrad Rudolph