-
September 23rd, 2004, 09:41 AM
#1
Dynamic Constructors in C++???
Can anyone explain me what are Dynamic Constructors in C++?
If possible give some example or provide with some reference article/link
Thanks in advance
-
September 23rd, 2004, 10:47 AM
#2
Re: Dynamic Constructors in C++???
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.
Code:
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).
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
-
September 24th, 2004, 12:44 AM
#3
Re: Dynamic Constructors in C++???
Hi Graham,
Thanks for the reply.
Even I hadn't heard about this so called "Dynamic Constructors"
But I was asked this question in an Interview. (Or did they actually meant Dynamic construction and it was mispelled as Constructor )
Thanks a lot
Regards,
Sohail
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|