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;
}
                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.
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;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With