I have several classes that have a common base class, for example:
class Base {};
class DerivedA : public Base {};
class DerivedB : public Base {};
class DerivedC : public Base {};
Now I need to know which of these derived classes need to be created at runtime (based on input). For example, if input "DerivedA", I need to create an object DerivedA. Input is not necessarily a string; it can be an integer. The fact is that there is some key, and I need a value corresponding to the key.
The problem is, how do I instantiate a class? C ++ does not have a built-in reflection such as C # or Java. A commonly suggested solution is to use the factory method as follows:
Base* create(const std::string& name) {
if(name == "DerivedA") return new DerivedA();
if(name == "DerivedB") return new DerivedB();
if(name == "DerivedC") return new DerivedC();
}
, , , , , . , std::map<std::string, ***>, , . AFAIK, . , factory, , factory , , .
, ?