Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get C++ object name in run time?

Tags:

c++

runtime

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.

like image 594
jackhab Avatar asked Jan 22 '09 12:01

jackhab


People also ask

How do I get the object name in R?

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.

How do you name an object in C++?

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).

How do you identify a class in C++?

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.

Do we have objects in C?

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.


2 Answers

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.

like image 140
jpalecek Avatar answered Oct 07 '22 05:10

jpalecek


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.

like image 29
KeithB Avatar answered Oct 07 '22 04:10

KeithB