Sign in to follow this  
nickwinters

Loading classes dynamically in C++

Recommended Posts

nickwinters    183
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

Share this post


Link to post
Share on other sites
Fruny    1658
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...)

Share this post


Link to post
Share on other sites
nilkn    960
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.

Share this post


Link to post
Share on other sites
Genjix    100
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).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this