How to create class objects dynamically?

The correct answer depends on the number of different classes of which you want to create the instances.

If the number is huge (the application should be able to create an instance of any class in your application), you should use the reflection functionality of .Net. But, to be honest, I’m not a big fan of using reflection in business logic, so I would advise not to do this.

I think that in reality you have a limited number on classes for which you want to create instances. And all the other answers make this assumption. What you actually need is a factory pattern. In the next code I also assume that the classes of which you want to create instances, all derive from the same base class, let’s say Animal, like this:

class Animal {...};
class Dog : public Animal {...}
class Cat : public Animal {...}

Then create an abstract factory which is an interface that creates an animal:

class IFactory
   {
   public:
      Animal *create() = 0;
   };

Then create subclasses for each of the different kinds of animals. E.g. for the Dog class this will become this:

class DogFactory : public IFactory
   {
   public:
      Dog *create() {return new Dog();}
   };

And the same for the cat.

The DogFactory::create method overrules the IFactory::create method, even if their return type is different. This is what is called co-variant return types. This is allowed as long as the return type of the subclass’s method is a subclass of the return type of the base class.

What you can now do is put instances of all these factories in a map, like this:

typedef std::map<char *,IFactory *> AnimalFactories
AnimalFactories animalFactories;
animalFactories["Dog"] = new DogFactory();
animalFactories["Cat"] = new CatFactory();

After the user input, you have to find the correct factory, and ask it to create the instance of the animal:

AnimalFactories::const_iterator it=animalFactories.find(userinput);
if (it!=animalFactories.end())
   {
   IFactory *factory = *it;
   Animal *animal = factory->create();
   ...
   }

This is the typical abstract factory approach.
There are other approaches as well. When teaching myself C++ I wrote a small CodeProject article about it. You can find it here: http://www.codeproject.com/KB/architecture/all_kinds_of_factories.aspx.

Good luck.

Leave a Comment