Arrays of many different (sub)classes

Robert Clipsham robert at octarineparrot.com
Sat Apr 24 12:16:49 PDT 2010


On 24/04/10 20:06, Joseph Wakeling wrote:
> 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

This should do what you want:
----
class BaseClass {
     // blah, blah ...
}

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

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

int main()
{
     BaseClass[] vec;
     vec ~= new A;
     vec ~= new C;
     // etc. etc.
}
----


More information about the Digitalmars-d-learn mailing list