Generally speaking, if you want to do something like
Base * createObject(string name)
{
return new <name_as_a_type>();
}
you will need a language with reflection so it is not possible in C++, but it is possible in, e.g., ruby. You can do some weird stuff in c++ if you particulary hate if
conditions, though I have no idea why would you do it:
class Base
{
public:
Base(int v)
{
std::cout << "base" << v << std::endl;
}
};
class Derived : public Base
{
public:
Derived(int v)
: Base(v)
{
std::cout << "derived" << v << std::endl;
}
};
class BaseFactory
{
public:
virtual Base * create(int value)
{
return new Base(value);
}
};
class DerivedFactory : public BaseFactory
{
Base * create(int value) override
{
return new Derived(value);
}
};
Base * createAwesomeness(string className, int parameter)
{
static std::map<string, BaseFactory *> _map = {
{"Base", new BaseFactory()},
{"Derived", new DerivedFactory()}
};
auto it = _map.find(className);
if(it != _map.end())
return it->second->create(parameter);
return nullptr;
}
int main()
{
auto b = createAwesomeness("Base", 0); //will construct a Base object
auto d = createAwesomeness("Derived", 1); //will construct a Derived object
return 0;
}