Polymorphic types should hide copy-ctor
Hi there,
Please excuse the newbiness, but having gone through Meyers' 3 books
and Sutter's first 2 books I cannot find an answer to this. I probably
haven't read them well, because this seems pretty basic. Could you
please sanity-check my understanding?
Alexandrescu's Modern C++, page 30, says that well-behaved polymorphic
types disable their copy-ctor, by making it private.
As I understand it, the rationale behind this is that copy
constructors, like all constructors, cannot be used polymorphically,
i.e.
Base *pBase = new Derived();
Base *pBase2(*pBase) // pBase gets sliced
So, to prevent this misuse, any polymorphic type/hierarchy that needs
copy semantics should instead implement a
virtual Base *Clone()
which returns a new object of the appropriate type, so for instance
Base *Derived::Clone() {
return new Derived(this); // invoke private copy-ctor
}
However, and this is my main question, how can Derived's copy-ctor
initialise the Base part correctly if Base's copy-ctor is not
accessible - since it's private? Shouldn't Base's copy-ctor be
protected instead?
Also, would it be OK to make public the copy-ctor of concrete (i.e.
leaf) classes?
As a side-question, could you please point me to any standard
literature outlining this idiom? The closest I could find was GoF's
Prototype design pattern, a hint in Sutter's "More Exceptional C+
+" (Item 31, page 193), and a similar discussion on copy-assignment
operators in Meyers' "More Effective C++" (Item 33, where however
AbstractAnimal::operator= is declared protected, not private).
Is this idiom what some people call "Virtual Constructor"?
Thank you very much,
Ichiro
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]