views:

463

answers:

6

Is it possible to know the object instance name / variable name from within a class method? For example:

#include <iostream>

using namespace std;

class Foo {
     public:
          void Print();
};

void Foo::Print() {
     // what should be ????????? below ?
     // cout << "Instance name = " << ?????????;
}

int main() {
    Foo a, b;
    a.Print();
    b.Print();
    return 0;
}
+11  A: 

No. Variable names are for the programmer, the compiler sees addresses.

Other languages that provide meta-data/reflection about their program might provide this functionality, C++ isn't one of those languages.

GMan
+10  A: 

Variable names do not exist in the compiled code.

However you can use some #define to get the name in preprocessing and let the names be populated before the compile.

Something like this:

#define SHOW(a) std::cout << #a << ": " << (a) << std::endl
// ...
int i = 2;
SHOW (i);
Svetlozar Angelov
+3  A: 

Variable names don't survive compilation. The best you can do is to pass the variable name into the object constructor and store it inside the object by using a macro. The latter will lead to really ugly code so you would only want this as a last resort.

sharptooth
A: 

It is not possible. C++ does not have a concept of "reflection" like .NET platform. But MFC library has CRunTime class - you can see for example.

Captain Comic
even with reflection you cant see the local variable names - just properties, methods and fields
Simon_Weaver
+7  A: 

Not with the language itself, but you could code something like:

#include <iostream>
#include <string>

using namespace std;

class Foo
{
 public:
    Foo(const string& name) { m_name = name;}
    void Print() { cout << "Instance name = " << m_name << endl; }

  private:
    string m_name;
};

int main() 
{
    Foo a("a");
    Foo b("b");

    a.Print();
    b.Print();

    return 0;
}
Steven
+5  A: 

What would that mean?

void f(T const& p) {
    cout << p.name();
}

T r() {
    T c;
    return c;
}

void g() {
    T a;
    cout << a.name();
    T & b = a;
    cout << b.name();
    T * ptr = &b; 
    cout << ptr->name();

    T d = r();
    cout << d.name();
}

What would you expect? "a" each time? And what about c/d?

Luc Hermitte