creating different instances of different classes

hi!

is there a better way to do something like this:

  
  
if (option == "Object1")  
{  
    Object1 obj = new Object1();  
}  
else if (option == "Object2")  
{  
    Object2 obj = new Object2();  
}  
else if (option == "AnotherObject")  
{  
    AnotherObject obj = new AnotherObject();  
}  
else if ...  
  

thanks for your help!

ben

Yes, there is. What you are looking for is the “factory design pattern”. Try a google search for “c++ factory design pattern” and implement what is most suitable for you.

Basically you store a string / functionpointer-pair into a map and then retrieve the function pointer when needed and create with that functionpointer your concrete class. One of the requirements is that all classes inherit from the same base-class.

HTH,
Stephan

yeah! thanks stephan! you are totally right!
got a solution from the boost irc, yay!

–> https://gist.github.com/1051577