Re: How to implement the virtual constructor behavour in C++
* zho_zhang11790@yahoo.com:
Hi, I know that in C++, there is no virtual constructor. But is there
any way to implement it by using the virtual function? For example:
We have a base class Shape, its constructor holds a string to indicate
what kind of shape we need to create. We also have three derived class
such as Square, Circle and Diamond. How to implement such kind of
behavour as following:
Square* ps = new Shape("Square");
Diamond* pd = new Shape("Diamond");
I guess the prototype design pattern may help. But I really don't know
how implement the above
behavour.
Any suggestions will be greatly appreciated
The simplest:
Square* ps = new Square;
Diamond* pd = new Diamond;
This also allows you to pass Square and Diamond-specific constructor
arguments.
Why is this unsatisfactory (if it is)?
{ Look up the web for "virtual constructors"; FAQ 20.8 also mentions them.
-mod/sk }
Uhm, that item refers to cloning, IIRC.
Some general-OO guru used the misleading term "virtual construction" for
cloning, and it was adopted in the FAQ, and once in, stuck.
The most relevant FAQ item for virtual function calls in the context of
construction came later on (my main contribution to the FAQ). It is the
item titled "Okay, but is there a way to simulate that behavior as if
dynamic binding worked on the this object within my base class's
constructor?", currently available at e.g. <url:
http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.6>.
Cheers,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]