user4352513
user4352513

Reputation:

C++/ How to instantiate an object based off user input

For example if the user inputs a string "modem", is there a way to instantiate an object of class Modem.

Or is there a much simpler way of doing this.

Upvotes: 1

Views: 813

Answers (3)

tmlen
tmlen

Reputation: 9090

A way to use std::map would be to add a static member function create to each subclass, like

class CDerived1 : public CBase {
public:
    static CBase* create() {
        return new CDerived1;
    }
}

And have a map of the function pointers:

typedef CBase*(create_function_t*)();
std::map<std::string, create_function_t > mapping = {
    {"modem", &CDerived1::create},
    ....
}

...

CBase* pBase = mapping[strText]();

Upvotes: 0

user2588666
user2588666

Reputation: 851

In this example, I would use the Factory Pattern. See http://www.oodesign.com/factory-pattern.html

Upvotes: 1

Mex
Mex

Reputation: 999

std::string strText = "modem";
CBase *pBase = nullptr;
if(strText == "modem")
    pBase = new CDervied1;
else
    pBase = new CDervied2;

Upvotes: 3

Related Questions