Make string of variable/member/class name

Mar 30, 2010 at 12:05pm
Is there a way to make a string of a class member name?
Let's say I have a class named MyClass with a member named mMember. mMember can be any type of object. I want to know if there is a macro or something where I can give mMember as an argument and get the string "mMember" in return? I would also like to be able to do the same with the class and get the string "MyClass" in return.

Many years ago, a friend showed me some code for this. It seemed very complicated but I remember he used _hook, _ref and CI_GET.


Thank you
Mar 30, 2010 at 12:41pm
I don't know about _hook, _ref and CI_GET. Maybe that's some stuff to use together with debug information compiled into some executables?

Anyway, for standard C++ means, there is no way to know the name of struct/class members. They are just for the compiler. You have to store them by yourself.


For classes, there is "RTTI". you can access a name of a class usable ONLY FOR DEBUG PURPOSE by doing typeid(myClass).name(). Typeid works only on primitive types (does it?) and on classes with at least one virtual function in it. It will give you the dynamic type, not the static one.

1
2
3
4
5
6
7
8
9
10
struct Foo { virtual ~Foo() {} }; // the struct has to have at least one virtual function.
struct Bar : Foo {};

int main () {
    cout << typeid(Foo).name() << endl; // prints someting like "Foo" or "struct Foo" (not guaranteed)
    Bar x;
    cout << typeid(x).name() << endl; // prints "Bar"
    Foo& f = x;
    cout << typeid(f).name() << endl; // prints "Bar". Not "Foo" (which would be the static type)
}


Note, that typeid().name is not your favourite swiss knive. It's not even sharp. There is exactly zero guarantee about how the string looks like you get back. There's only a recomendation that it should look readable to programmers, so you probably won't get "123@$$%2" or so. Hopefully. :-D

MSVC returns "struct Foo".

Ciao, Imi.
Last edited on Mar 30, 2010 at 12:43pm
Topic archived. No new replies allowed.