Search code examples
oopstaticd

Using a static member variable to count number of objects created


I am trying to create a dynamic array of objects, using a static variable as a pointer to the next available array index. I'm sure there is a better way to do this...

class storing the dynamic array:

import std.stdio;

import DataRow;

class Database{

public:
    this(){ /* intentionally left blank */}

    void addRow(DataRow input){
        this.db[count] = input;
        writeln(count);
        count++;
    }

private:
    static uint count;
    DataRow[] db;
}

Solution

  • D arrays can be appended to with the ~= operator, and keep track of their own length. You shouldn't need to keep track of the length yourself:

    void addRow(DataRow input){
        this.db ~= input;
        writeln(db.length); // number of rows in db
    }
    

    Based on your example, I'm not sure if this is what you intended. Each Database instance has its own member db, but all would share the same count variable as you declared it as static. Unless you have a good reason for keeping a static counter (which would track the number of rows added across all instances of Database), I would just rely on each array to track its own length.