Arrays of many different (sub)classes

Joseph Wakeling joseph.wakeling at webdrake.net
Sat Apr 24 12:06:23 PDT 2010


Hello all,

Occasionally in C++ I find it useful to build an array which contains
classes of multiple different types all using the same interface -- by
constructing an array of pointers to some common base class, e.g.

class BaseClass {
    // blah, blah ...
};

class A : BaseClass {
    // ... blah ...
};

class C : BaseClass {
    // ... blah ...
};

int main()
{
    vector<BaseClass *> vec;
    vec.push_back(new A());
    vec.push_back(new C());
    // etc. etc.
}

(This code might be wrong; I'm just typing it to give the idea.  And in
practice, I usually do not use 'new' statements but pass pointers to
already-existing objects...:-)

Anyway, the point is that at the end of the day I have an array of
different objects with a common interface.  What's the appropriate way
to achieve the same effect in D?

Thanks & best wishes,

    -- Joe


More information about the Digitalmars-d-learn mailing list