AFAIK, at least with general C++, there's no implicit way to create a class using just a string. However, there is another mechanism I have used in the past.
Firstly, you define the notion of a component:
class Component /* or IComponent if you're feeling adventurous - we may not have interfaces in C++, but dammit we like 'em! */
{
protected:
Component() { };
public:
virtual ~Component() = 0 { };
}; // eo class Component
And a notion of a some kind of creator:
class ComponentCreator
{
protected:
Component() { };
public:
virtual ~ComponentCreator() = 0 { };
virtual Component* create() const = 0; // Might want to use smart-pointers here - this is for illustrative purposes only.
}; // eo class ComponentCreator
Ok, we have the basics now we need a factory that can have these creators registered against it:
class Factory
{
private:
std::map<std::string, ComponentCreator*> _creators;
public:
Factory() : _creators(new std::map<std::string, ComponentCreator*>();
{
};
~Factory()
{
// cleanup of _creators ommited.
};
// call to register a creator
void register(const std::string& name, ComponentCreator* creator)
{
// normally you'd put checks to see if it exists etc.
_creators[name] = creator;
}; // eo register
// call to create an instance
Component* create(const std::string& name)
{
std::map<std::string, ComponentCreator*>::const_iterator cit(_creators.find(name));
if(cit != _creators.end())
return cit->create();
else
return NULL; // or nullptr
}; // eo create
}; // eo class Factory
Declare your classes thusly (I will do just one):
class ComponentA : public Component { /* implementation */ };
And don't forget the creator:
class ComponentCreatorForA : public ComponentCreator
{
public:
virtual Component* create() const { return new ComponentA(); };
}; // eo class ComponentCreatorForA
During initialisation of your program, you register component creators:
factory.register("componentA", new ComponentCreatorForA());
factory.register("componentB", new ComponentCreatorForB());
And later on, we can then create components by name:
Component* component = factory.create("componentA");
Notes:
This approach assumes components are known at compile-time. If not one could introduce a plugin-architecture so that additional DLLs can register their components via the factory on start-up so you could make it extensible without having to re-deploy everything.
In the real world we'd use smart pointers of some such, and typedef a lot of that stuff away to make it easier on typing!