How to get C++ object name in run time?
The language does not give you access to that information.
By the time the code has been compiled all named objects have been translated into relative memory locations. And even these locations overlap because of optimization (ie once a variable is no longer in use its space can be used by another variable).
The information you need is stored in the debug symbols that are generated by most compilers but these are usually stripped from release versions of the executable so you can not guarantee they exist.
Even if the debug symbols existed they are all compiler/platform specfic so your code would not be portable between OS or even compilers on the same OS. If you really want to follow this course you need to read and understand how the debugger for your platform works (unless you have already written a compiler this is very non trivial).
Its not possible. For on thing, an object doesn't have a unique name.
A a;
A& ar = a; // both a and ar refer to the same object
new A; // the object created doesn't have a name
A* ap = new A[100]; // either all 100 objects share the same name, or need to
// know that they are part of an array.
Your best bet is to add a string argument to the objects constructor, and give it a name when its created.
Since objects in C++ don't have any names, you cannot get them. The only thing you can get to identify an object is its address.
Otherwise, you can implement your naming scheme (which means the objects would have some char*
or std::string
member with their name). You can inspire yourself in Qt with their QObject hierarchy, which uses a similar approach.
This may be GCC-specific:
#include <typeinfo>
#include <iostream>
template <typename T>
void foo(T t)
{
std::cout << typeid(t).name() << std::endl;
}