Constructors (starstruck noob from C++)

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Thu Jan 20 19:02:42 PST 2011


On 1/20/11 7:18 PM, Luke J. West wrote:
> Hi to all from a total noob.
>
> first of all, I'd like to say how impressed I am with D. In fact, I keep
> pinching myself. Have I *really* found a language worth leaving C++ for
> after two decades? It's beginning to look that way. Obviously I'm
> devouring the 2.0 documentation right now, but have not yet found out
> how to create a new instance of an existing class object. What I mean
> is, given...
>
> auto a = new A;
>
> how do I, in c++ speak, do the D for...
>
> A  b(a); // or if you prefer...
> A* b = new A(a);
>
> I'm sure this must be trivial.
>
> Many many thanks,
>
> Luke

Hopefully this won't mark a demise of your newfound interest :o). If A 
were a struct, auto b = new A(*a) would do. For classes, D does not 
provide automatic copy constructors; you need to define and follow a 
sort of cloning protocol.

That being said, it's not difficult to define a generic function that 
copies fields over from one class object to another. Here's a start:

import std.stdio;

void copyMembers(A)(A src, A tgt) if (is(A == class)) {
     foreach (e; __traits(allMembers, A)) {
         static if (!is(typeof(__traits(getMember, src, e)) == function)
                    && e != "Monitor")
         {
             __traits(getMember, tgt, e) = __traits(getMember, src, e);
         }
     }
}

class A {
     int x = 42;
     string y = "hello";
     final void fun1() {}
     void fun2() {}
     static void fun3(){}
}

void main() {
     auto a = new A;
     a.x = 43;
     auto b = new A;
     copyMembers(a, b);
     assert(b.x == 43);
}

I think copyMembers belongs to the standard library. I wanted to define 
a family of functions like it but never got around to it.


Andrei


More information about the Digitalmars-d mailing list