Newbie: copy, assignment of class instances

Simen kjaeraas simen.kjaras at gmail.com
Thu May 20 12:18:51 PDT 2010


Larry Luther <larry.luther at dolby.com> wrote:

> Given:
>
>   class A {
>     int x, y;
>   }
>
>   class B : A {
>     int z;
>   }
>
>   B
>     foo = new B,
>     bar = new B;
>
>   scope B
>     alpha = new B;
>
> Q1:  How do I copy the member variables contributed by base class A
>      from "foo" to "bar"?
>      In C++:  (A &) bar = foo;

You can't. If you need this functionality, use a specialized function.

> Q2:  How do I do a deepcopy of foo to bar?
>      In C++:  bar = foo;

You don't. If you need this functionality, use a specialized function.
This should, to keep symmetry with other D features, probably be
called dup. Possibly deepdup, as the other dups don't do deep copy.

It is also worth noting that 'bar = foo;' does not perform deep copying
in C++, it only copies the immediate members, whereas deep copy would
follow pointers and deep copy those, too.

btw, if what you're referring to is not the deep copy explained above,
but merely a shallow copy (of the instance, not the reference), the
function should be called dup.

> Q3:  Is the object "alpha" on the stack (per documentation)?

Yes. Proof:

void main( ) {
     A a = new A( );
     scope A b = new A( );
     writefln( "%p, %p, %p", cast(void*)a, cast(void*)b, cast(void*)&a );
}

> Q4:  What happens when I do "alpha = foo;"?
>      "printf( "%p\n", alpha);" indicates that the address of "alpha" has  
> changed.

'scope B alpha;' allocates stack space for a reference to a B, and
space for an instance of B. If the pointer changes, it is simply no longer
referencing the instance on the stack.

-- 
Simen


More information about the Digitalmars-d-learn mailing list