0

I have a string and want to use it as struct name dynamically.

struct employee{

atributes ....
} 

string name;
cin >>name;


employee "name"

and then use the named employee !

does not work

employee &name = new employee();

does not work

  • 1
    Where did you find the syntax `employee &name = new employee();`? C++ is not a language where you can write the first thing that comes to mind (even adapted from another language) and expect it to work. The best course of action isn't someone telling you the exact syntax, but learning from a good introductory book. – Luchian Grigore Sep 03 '14 at 11:12
  • You can't do that. Perhaps you should explain what problem you are trying to solve that has caused you to come up with this proposed solution. – molbdnilo Sep 03 '14 at 11:33
  • C++ is not javascript. One is static the other is dynamic, and you just stepped on one of the core differences :) – Drax Sep 03 '14 at 12:56

2 Answers2

4

This is not possible in C++. Look at the concept of associative containers to store named references to class/struct instances, for example an std::map<std::string, employee>. This creates a 'map' class mapping string based keys to values of type employee.

More practical examples here.

Community
  • 1
  • 1
Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
4

Indeed, you can't use run-time string values as variable names. You could use a map to index objects by a string or other key type:

#include <map>

std::map<std::string, employee> employees;

employees[name] = employee();
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644