virtual constructor

Discussion in 'C++' started by uday, Nov 25, 2004.

  1. uday

    uday Guest

    can u explain me the concept of virtual constructor. Does such concept
    exists in c++
     
    uday, Nov 25, 2004
    #1
    1. Advertising

  2. "uday" <> wrote...
    > can u explain me the concept of virtual constructor. Does such concept
    > exists in c++


    Read the FAQ.
     
    Victor Bazarov, Nov 25, 2004
    #2
    1. Advertising

  3. > 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
     
    Jonathan Mcdougall, Nov 25, 2004
    #3
  4. Victor Bazarov, Nov 25, 2004
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Giulio
    Replies:
    9
    Views:
    1,066
    Patrick Kowalzick
    Jun 25, 2003
  2. Brett Irving
    Replies:
    3
    Views:
    3,349
    John Harrison
    Jun 29, 2003
  3. lallous
    Replies:
    5
    Views:
    8,870
    David Harmon
    Jan 23, 2004
  4. Aire
    Replies:
    3
    Views:
    486
    Mike Wahler
    Jan 25, 2004
  5. Generic Usenet Account
    Replies:
    10
    Views:
    2,340
Loading...

Share This Page