Object oriented programming and interfaces

Adam D. Ruppe destructionator at gmail.com
Mon Dec 4 21:04:06 UTC 2017


On Monday, 4 December 2017 at 20:43:27 UTC, Dirk wrote:
> interface Medoid {
>     float distance( Medoid other );
>     uint id() const @property;
> }
>
> and a class implementing that interface:
>
> class Item : Medoid {
>     float distance( Item i ) {...}
>     uint id() const @property {...}
> }
>
> The compiler says:
> Error: class Item interface function 'float distance(Medoid 
> other)' is not implemented
>
> Is there a way to implement the Item.distance() member function 
> taking any object whose class is Item?


So what would happen there if someone did:

Medoid i = new Item();
i.distance(new OtherMedoid());

What does it call there?


The OtherMedoid isn't an Item, so your Item.distance method 
wouldn't work... meaning it didn't actually implement the 
interface.

Item.distance CAN take any Item, that function is legal... it 
just doesn't impelment the interface since it isn't broad enough 
to take anything the interface can take. So remove it from the 
interface or implement a generic version too.


More information about the Digitalmars-d-learn mailing list