Arrays of many different (sub)classes

Robert Clipsham robert at octarineparrot.com
Sun Apr 25 10:11:09 PDT 2010


On 25/04/10 14:47, Joseph Wakeling wrote:
> Robert Clipsham wrote:
>> This should do what you want:
>
> Thanks! :-)
>
> Is it possible to do this with an interface instead of a base class?
> I'm not familiar with how the former work ...
>
> Best wishes,
>
>      -- Joe

Yes it is, providing the base doesn't implement any methods, eg:

----
interface I
{
   int foobar();
   // The following line will cause an error when uncommented, as
   // you cannot implement methods in an interface
   // void baz() {}
}

class C : I
{
   int foobar() { return 1; }
}

class D : I
{
   int foobar() { return 2; }
}

import std.stdio;

void main()
{
   I[] arr;
   arr ~= new C;
   arr ~= new D;
   foreach( el; arr )
     writefln( "%d", el.foobar() );
}
----
Prints:
1
2

You could also use an abstract class instead of an interface if you want 
to implement some of the methods.


More information about the Digitalmars-d-learn mailing list