Loading classes dynamically in C++

Started by
2 comments, last by Genjix 19 years ago
I have a data file which tells me what class to load. Is there a way to pass in a string with the name of the class and get a pointer to that type? In C#, I would just use reflection to do this. Does C++ have an equivalent? Or would you advise I just use a scripting language for these classes? Thanks. -Nick
Advertisement
C++ can't refer to types by name; nor does it support reflection. You'll have to store the correspondance in some data structure (e.g. a std::map). What you are looking for is called a Factory (Object Factory/Abstract Factory/Generic Factory/Factory Pattern...)
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
You need what is called Pluggable Factories. Here's some basic code to do it, should mostly be self-explanatory:

typedef std::string ObjectType;template<class Base>class CreatorBase{public:    virtual ~CreatorBase() {}    virtual Base * Create() const = 0;};template<class Product, class Base>class Creator : public CreatorBase<Base>{public:    virtual Base * Create() const {return new Product;}};template<class Base>class Factory{public:    Base * Create(ObjectType type);    bool Register(ObjectType type, CreatorBase<Base> * pCreator);private:    typedef std::map<ObjectType, CreatorBase<Base> *> CreatorMap;    CreatorMap m_creatorMap;};template<class Base>bool Factory<Base>::Register(ObjectType type, CreatorBase<Base> * pCreator){    CreatorMap::iterator it = m_creatorMap.find(type);    if (it != m_creatorMap.end()) {        delete pCreator;        return false;    }    m_creatorMap[type] = pCreator;    return true;}template<class Base>Base * Factory<Base>::Create(ObjectType type){    CreatorMap::iterator it = m_creatorMap.find(type);    if (it == m_creatorMap.end())         return NULL;    CreatorBase<Base> * pCreator = (*it).second;    return pCreator->Create();}


I just grabbed that code really quickly from all my helper code I use for my projects. You seem experienced with programming, so hopefully you understand what it's doing. If not, just ask and I'll explain in further detail.

Edit: here is an article discussing them in detail.
you could dynamically load in .o or .dll (whatever os your using) files and have provided in them entry and exit classes/functions (i.e a static function to return a new instance of your class).

This topic is closed to new replies.

Advertisement