virtual constructor

J

Jonathan Mcdougall

can u explain me the concept of virtual constructor. Does such concept
exists in c++

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);
}


Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top