How can I create an instance of an object, knowing only its name?

Possible duplicate:
Is there a way to create objects from a string containing their class name?

In C ++, I want my user to enter an object type name that should be created at runtime, and, depending on the line I get from them, the program will instantiate the correct object (in short, I am implementing a method template factory). However, if the program must support a new type of object, then changing the existing code is not allowed.

Thus, you can delete everything if if else, if ... else if ... stuff from the method, and still my program creates an instance of the correct object of a certain type of product (from many that are known only at compile time)?

My searches around me got this link: Is there a way to create objects from a string containing their class name? and it seems like I want, but I don’t understand the code at all.

Any help would be really appreciated.

+5
source share
2 answers

This will only work if all the necessary classes are derived from some common base class, and you will usually be limited to using the base interface (although you can get around this with some extra effort). Here is one approach:

// Immutable core code:

#include <map>
#include <string>

class Base
{
  typedef Base * (*crfnptr)(const std::string &);
  typedef std::map<std::string, crfnptr> CreatorMap;

  static CreatorMap creators;

public:
  virtual ~Base() { }
  Base * clone() const { return new Base(*this); }

  static Base * create_from_string(std::string name)
  {
    CreatorMap::const_iterator it = creators.find(name);
    return it == creators.end() ? NULL : it->first();
  }

  static void register(std::string name, crfnptr f)
  {
    creators[name] = f;
  }
};

Now you can add new derived classes from your new code:

// your code:

#include "immutable_core.hpp"

class Foo : public Base
{
public:
  Foo * clone() const { return new Foo(*this); }
  static Foo * create() { return new Foo; }
};

Base::register("Foo", &Foo::create);

To create a class, you simply call Base * p = Base::create_from_string("Foo");.

+5
source

, - . Linux dlopen. , , .

: ++ dlopen mini HOWTO

+2

All Articles