I have a class say class A and a string variable string name = "student"
. I want to create an instance of class A with the object name as student say class A student;
But i don't know the name of object prior; I have the object name present in the string variable.
Any suggestions on how to do this?
Asked
Active
Viewed 73 times
0

Swordfish
- 12,971
- 3
- 21
- 43

LoneWolf97
- 21
- 2
-
If it helps you, name them generically and save a name within the class. – skratchi.at May 06 '19 at 06:49
-
7Why do you want to do that? How would you use a variable whose name you don’t know? – molbdnilo May 06 '19 at 06:50
-
@molbdnilo i back that observation^^ did not think about it, but you are very right. – skratchi.at May 06 '19 at 06:50
-
2We don't know what real problem you are trying to solve, but whatever it is you are probably looking for a `std::map`. That data structure lets you associate arbitrary data with a string. – john May 06 '19 at 06:51
-
It sounds like maybe [`std::map`](https://en.cppreference.com/w/cpp/container/map) or [`std::unordered_map`](https://en.cppreference.com/w/cpp/container/unordered_map) could be what you're looking for. – Miles Budnek May 06 '19 at 06:51
-
4You might be confusing objects (which exist only when the program runs) with variables (which exist only in source code). If you want to name *objects*, you need to store the names somehow and associate them with the objects, for instance in a table. – molbdnilo May 06 '19 at 06:52
-
1Sounds like an [XY Problem](https://en.m.wikipedia.org/wiki/XY_problem). – Paul R May 06 '19 at 07:06
-
yes basically this is sub problem from the main problem i am trying to solve..Anyways I understood that we cant do that... – LoneWolf97 May 06 '19 at 09:06
1 Answers
1
You simply can't do that. There are no variable names once the code has been compiled.

Swordfish
- 12,971
- 3
- 21
- 43