Re: Cloning
On Jul 8, 6:40 am, Andrey Tarasevich <andreytarasev...@hotmail.com>
wrote:
pauldepst...@att.net wrote:
Suppose class B is derived from class A As a public member funct=
ion
in class B, there is a clone
A* clone() const {return new B(*this);}
When and why would this be preferred to B* clone() const{return new
B(*this);}
Well, always. It is always better to specify the return type that
describes the actual type of the object being returned as closely as
possible.
With an issue as generic as this one, there are so many examples when
this might come useful that it is hard to choose just one.
Imagine, for example, that somewhere in your code you'd have to work
with the polymorphic class hierarchy rooted at 'B', possibly with some
specific interface features that originate in 'B' (but not present in
'A'). The code does not care, does not know, and does not need to know
about the rest of the hierarchy. With regard to the above 'clone'
function this is immediately and naturally achievable when the return
type is declared as 'B*'. Without it you'd have to use an explicit cast
to forcefully convert the return value to 'B*' type.
Also, you might need to call 'B::clone' is a completely non-polymorphic
context (like "I know a have a 'B' and I know I will get a 'B' from the
clone function"), where the return type of 'A*' looks simply ridiculous
and requires workarounds to make it work.
--
Best regards,
Andrey Tarasevich
Thanks. However, just to clarify, I don't think you meant "Well,
always", but rather "Well, never."
After starting this thread, I read (from 2004), in reference to
B* clone() const{return new B(*this);}
"Many compilers will not compile this syntax, as this is an exception
to the general rule that you cannot override the return type of a
virtual function."
Paul Epstein