Note: This website is archived. For up-to-date information about D projects and development, please visit

Arrays of classes

Part of ArraysCategory


How to allocate arrays of classes and pass them to functions.


import std.c.stdio;
import std.string;

class A {    
    int n;
    this(int n1)
        n = n1;
        // we are in the constructor
        printf("Constructor (n = %d)\n", n);
    // operator to convert class A to a string
    char[] toString()
        char[] ris;
        ris = .toString(n);
        return ris;

void Print(A[] a)
    // print all the elements of array "a"
    for (int i = 0; i < a.length; i++) {
        printf("A%.*s\n", .toString(a[i].n));

int main(char[][] args)
    A[] a;
    // allocate the memory
    a.length = 5;
    // i is a counter, j gets a pointer to A
    foreach (int i, A j; a) {
        // allocate the element j and copy the reference to a[i]
        a[i] = j = new A(i);
        printf("A%.*s\n", j.toString());
    return 0;


Posted by Anonymous