Dynamic constructor

Discussion in 'C++' started by shashidara, Feb 6, 2010.

  1. shashidara

    shashidara New Member

    Joined:
    Feb 6, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    What are dynamic constructors and how do we use dynamic constructors in C++ to concatenate two strings?
     
  2. Poonamol

    Poonamol New Member

    Joined:
    Mar 31, 2010
    Messages:
    33
    Likes Received:
    0
    Trophy Points:
    0
    I've not heard the term Dynamic Constructor used, but I'll take a guess that it's equivalent to the so-called "virtual constructor" or "clone method".

    Basically, it's a way of constructing an object based on the run-time type of some existing object. It basically uses standard virtual functions/polymorphism.

    class base
    {
    public:
    virtual base* create() = 0;
    virtual base* clone() = 0;

    protected:
    base();
    base(const base&);
    };

    virtual der1 : public base
    {
    public:
    base* create() { return new der1; }
    base* clone() { return new der1(*this); }
    // etc...
    };

    virtual der2 : public base
    {
    public:
    base* create() { return new der2; }
    base* clone() { return new der2(*this); }
    // etc...
    };

    int main()
    {
    base* b = new der1;

    base* b1 = b->create();
    base* b2 = b->clone();
    }

    In the above, if I change the initialisation of b so that it points to a der2, then b1 and b2 will also point to a der2 object (a brand new one in the case of b1, and a copy of *b in the case of b2).
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice