NULLPTR
NULLPTR

Reputation: 37

Get the name of an instance of a class in C++?

Lets say we have this class

class IntArray {

string name;



};

and we have this driver

 int main(){

 IntArray xe;



 return 0;
 }

Basically, how would we store that name of the instance, the "xe" through the constructor and into the data member "string name"?

Upvotes: 0

Views: 468

Answers (3)

Luis Colorado
Luis Colorado

Reputation: 12635

Well, you have some trick to solve your problem. Instead of using directly the constructor, just use a macro, like:

#define DECL(x) x(#x)

in some common header you #include in your application. Instead of declaring

IntArray ex;

do

IntArray DECL(ex);

on expansion, you will get something like:

IntArray xe("xe");

you can also use the variadic macro expansion of latest standards to be able to call a different constructor.

#define DECL(name, ...) name(#name, #__VA_ARGS__)

If you want, you can also include the type in the macro, so:

#define DECL(type, name) type name(#type, #name)

and declare your variable with:

DECL(IntArray, ex);

That will expand to:

IntArray ex("IntArray", "ex");

this trick is far from complete, but can help you to avoid mistakes because of mispelling variable names as a consequence of having to write twice in source code.

Upvotes: 1

einpoklum
einpoklum

Reputation: 131405

C++ does not support doing this. Variable names are only something you as a developer are aware of. The compiled program doesn't have them. Your std::string name field inside the class IntArray would not hold "xe"; it would just be uninitialized.

You could, however, use a map - an std::unordered_map<std::string, IntArray> arrays to be exact - and then use arrays["xe"] to access the array you like using a runtime-defined string. See std::unordered_map on CPPReference for details.

Upvotes: 6

Swordfish
Swordfish

Reputation: 13134

#include <string>

class IntArray
{
    std::string name;
public:
    IntArray(std::string name) : name{ std::move(name) } {}
};

int main()
{
    IntArray xe{ "xe" };
}

Upvotes: 1

Related Questions