Can I get an object's name in run time (like getting an object's type via RTTI)? I want the object to be able to print its name.
names() function in R Language is used to get or set the name of an Object. This function takes object i.e. vector, matrix or data frame as argument along with the value that is to be assigned as name to the object. The length of the value vector passed must be exactly equal to the length of the object to be named.
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).
Defining Class and Declaring Objects A class is defined in C++ using keyword class followed by the name of class. The body of class is defined inside the curly brackets and terminated by a semicolon at the end.
In terms of C programming, an object is implemented as a set of data members packed in a struct , and a set of related operations. With multiple instances, the data for an object are replicated for each occurrence of the object.
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.
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.
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