Search code examples
c++classconstructorinstance

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;
}

Solution

  • 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;
    }