You cannot use the ctor from the base class to build a subobject, because by definition the constructor only initializes fields of current class.
You can use a static factory method in the base class, but because of C++ object slicing the factory method cannot return an Enemy
- I you do, you will only get a raw Enemy
copying common fields from the subclass object created. A more idomatic way would be to return a pointer to a newly created object, or better a smart pointer:
class Enemy
{
public:
Enemy();
virtual ~Enemy();
static std::unique_ptr<Enemy> build_enemy() {
// get random number in choice
Enemy * enemy;
switch (choice) {
case 0: enemy = new Ghost(); break;
default: enemy = new Orc(); break;
}
return std::unique_ptr(enemy);
}
};
If for any reason you prefere arrays of functions to switches, they can be used easily here:
class Enemy
{
public:
Enemy();
virtual ~Enemy();
static unique_ptr<Enemy> build_enemy();
private:
typedef Enemy* (*Builder)();
static Enemy* buildGhost();
static Enemy* buildOrc();
static Builder builder[];
};
class Ghost: public Enemy
{
};
class Orc: public Enemy
{
};
Enemy* Enemy::buildGhost() {
return new Ghost();
}
Enemy* Enemy::buildOrc() {
return new Orc();
}
std::unique_ptr<Enemy> Enemy::build_enemy() {
// get random choice
Enemy *enemy = (builder[choice])();
return std::unique_ptr<enemy>;
}
Enemy::Builder Enemy::builder[] = { Enemy::buildGhost, Enemy::buildOrc };