Confused about interfaces in D

ylixir ylixir at gmail.com
Thu Oct 2 08:41:45 PDT 2008


Thomas Leonard wrote:
> Hi,
> 
> I'm used to interfaces in Java, and I'm wondering why this doesn't work 
> in D:
> 
>   interface Clock {}
> 
>   class SystemClock : Clock {}
> 
>   void main(string[] args) {
> 	Clock c = new SystemClock();
> 	c.toString();
>   }
> 
> It says:
> 
>   $ dmd clock.d
>   clock.d(7): Error: no property 'toString' for type 'clock.Clock'
> 
> This compiles, though:
> 
> 	Clock c = new SystemClock();
> 	(cast(Object) c).toString();
> 
> When is a "Clock" not an "Object"?
> 
> Thanks,

"Clock" is never an "Object".  Object is a class every other class is 
implicitly inherited from, and interfaces cannot be derived from 
classes, otherwise you would wind up with the nastiness that makes 
multiple inheritance in c++ such a nightmare (diamond shaped inheritance 
trees, etc), and would in fact eliminate the need for interfaces altogether.

casting c to Object works because SystemClock inherits from Object, 
without the cast it doesn't work because Clock is not inherited from Object.

Maybe i'm missing something, as others seem to be going on about COM 
programming, but i don't think this has anything to do with COM, it's 
simply that D doesn't support multiple inheritance, with good reason.


More information about the Digitalmars-d-learn mailing list