1

I am in a situation that I need to make objects in runtime that are named by value of a string, but I can't do that:

cin>>input;
className "input"= new className;

How can I do that?

I think it is possible to achieve by using maps. Is it true?

UmFraWJ1bCBJc2xhbQ
  • 4,101
  • 6
  • 24
  • 41
comp94 ui
  • 31
  • 5

2 Answers2

4

As you said, you can achieve your goal by using std::map (or std::unordered_map)

map<string, className*> aMap;//map a string to a className pointer/address
cin>>input;
aMap[input] = new className; //input is mapped to a className pointer

Then you can treat aMap[input] as a className*. e.g.

To call a className method, you can:

aMap[input]->aClassNameMethod();
gchen
  • 1,165
  • 1
  • 5
  • 12
1

The object oriented way would be to make name a member of that class and use the input to construct the class.

#include <string>
#include <iostream>

class Foo
{
    std::string myName;
public:
    // Constructor assigning name to myName.
    Foo(const std::string name) : myName(name) {} 

    std::string GetMyName() const
    {
        return myName;
    }
};

int main()
{
    std::string input;
    std::cin >> input;
    Foo f(input);
    std::cout << f.GetMyName();
}

Also read about new in C++: Why should C++ programmers minimize use of 'new'?

Roi Danton
  • 5,515
  • 4
  • 44
  • 62