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

3
  • 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. Commented Sep 3, 2014 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. Commented Sep 3, 2014 at 11:33
  • C++ is not javascript. One is static the other is dynamic, and you just stepped on one of the core differences :) Commented Sep 3, 2014 at 12:56

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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();

2 Comments

@NielsKeurentjes Uhm what?!?
Erm my bad, read too quick. Sorry :) Shouldn't pick up the phone while writing answers...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.