Taking a copy of an object
kris
foo at bar.com
Tue Aug 8 09:45:01 PDT 2006
Bruno Medeiros wrote:
> kris wrote:
>
>>
>> BTW: one concern I'd have with a root-Object dup() method is the need
>> to cast the returned instance. Presumeably a more specific compiler
>> implementation (of object.dup) would sidestep that need for casting?
>
>
> There is no need for casting. Since D supports covariant return types,
> the overriding methods can return their specific types:
>
> class Foo {
> Foo Clone() {
> return new Foo();
> }
> }
>
> class FooBar : Foo {
> override FooBar Clone() {
> return new FooBar();
> }
> }
>
Yes, we're well aware of the covariance aspect. However, we'd been
talking about /one/ method to handle all shallow class copy (perhaps in
the root Object, as was noted). Why one method? So (a) you don't have to
add the above to each and every class that might possibly be copied at
some point in the future, and (b) you don't end up being confused when
you dup a class and wind-up with a partial copy (and a cast requirement)
when a superclass method is invoked instead.
Covariance is all well and good, but we stepped beyond that point early
on. Perhaps you'll re-read the first paragraph again and understand it
better?
More information about the Digitalmars-d
mailing list