Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Dynamic constructor (http://www.go4expert.com/forums/dynamic-constructor-t20885/)

shashidara 6Feb2010 16:26

Dynamic constructor
What are dynamic constructors and how do we use dynamic constructors in C++ to concatenate two strings?

Poonamol 29Apr2010 12:23

Re: Dynamic constructor
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
virtual base* create() = 0;
virtual base* clone() = 0;

base(const base&);

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

virtual der2 : public base
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).

All times are GMT +5.5. The time now is 18:35.