Dynamic constructor

shashidara's Avatar, Join Date: Feb 2010
Newbie Member
What are dynamic constructors and how do we use dynamic constructors in C++ to concatenate two strings?
0
Poonamol's Avatar, Join Date: Mar 2010
Go4Expert Member
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).