Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a C++ Class Constructor Know Its Instance Name?

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;
}
like image 539
Adam Dempsey Avatar asked Nov 25 '09 09:11

Adam Dempsey


2 Answers

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.

like image 156
GManNickG Avatar answered Oct 12 '22 03:10

GManNickG


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

#include <iostream>
#include <string>

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

  private:
    std::string m_name;
};

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

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

    return 0;
}
like image 27
Steven Keith Avatar answered Oct 12 '22 05:10

Steven Keith