virtual constructor

招聘網站評價

That's a design pattern, not a built-in construct.

From the language's POV, the actual virtual function called depends on
the object on which it is called. Having a virtual constructor makes no
sense because there are no objects yet.

Still, it should be possible to create different type of objects
depending on a given object. For exemple, having an object of type
SillyMonsterCreator would create SillyMonster's and an object of type
BadMonsterCreator would create BadMonster's. The Virtual Constructor
pattern is also called Factory.

class Monster
{};

class SillyMonster : public Monster
{};

class BadMonster : public Monster
{};

class MonsterCreator
{
public:
virtual Monster *create() = 0;
};

class SillyMonsterCreator : public MonsterCreator
{
public:
SillyMonster *create() { return new SillyMonster; }
};

class BadMonsterCreator : public MonsterCreator
{
public:
BadMonster *create() { return new BadMonster; }
};


void f(MonsterCreator &creator)
{
// that's our virtual contructor call
Monster *m = creator.create();

// here we have a monster of some type, depending on 'creator'

delete m;
}


int main()
{
SillyMonsterCreator smc;
BadMonsterCreator bmc;

// let`s create a silly monster
f(smc);

// let's create a bad monster
f(bmc);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章