Search code examples
arraysconstructorddynamic-arrays

Using constructors with arrays in D


How do you call constructors when allocating an array with new?

For example, in the following code how would I call the constructor for each instantiation of A, initialising b to 5 for all 10 elements?

void main() {
    A[] a = new A[10];
}

class A {
    int b;
    this(int init) {
        b = init;
    }
}

I'm guessing it's not possible, but I can hope...


Solution

  • a simple loop should do (and it's the most readable)

    foreach(ref el;a){
        el=new A(5);
    }
    

    or you can use the array initializer:

    A[] a=[new A(5),new A(5),new A(5),new A(5),new A(5),
           new A(5),new A(5),new A(5),new A(5),new A(5)];