Hello, I'm working on a game and am trying to implement a smart way to create npc-objects in C++ from parsing a text file.
Currently this is hard coded in a Factory-object. Like this:
IActor * ActorFactory::create(string actortype, Room * r, string name, int hp)
{
if(actortype == "Troll")
{
return new Troll(r, name, hp);
}
if (actortype == "Dragon")
{
return new Dragon(r, name, hp);
}
// ... and so on
throw "Can't recognize type '"+actortype+"'.";
}
This is in my opinion a very ugly way to do it. Since it (among other things) breaks the Open/Closed principle.
I am schooled in Java, and in Java I would do something like having each IActor report it's class name and class type to the ActorFactory in the beginning of program execution. The factory would then store the relation in a map and can then easily look up what string maps to which object and it can then easily instantiate it.
Edit: I would also like to have the ability to call the constructor with a variable number/type of arguments.
How would this be done in C++? Can it be done?