toString() through interface

David Held via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Apr 19 17:35:22 PDT 2014


interface Foo { }

class Bar : Foo
{
     override string toString() pure const { return "Bar"; }
}

void main()
{
     Foo foo = new Bar;
     foo.toString();
}

src\Bug.d(14): Error: no property 'toString' for type 'Bug.Foo'

Since all implementations of an interface must derive from Object, why 
can't we access Object's methods through the interface?  Even explicitly 
casting to Object doesn't help:

     cast(Object)(foo).toString();

Same error message.  Now here is where things get weird:

     Object baz = foo;

src\Bug.d(15): Error: cannot implicitly convert expression (foo) of type 
Bug.Foo to object.Object

Orly?!?  I'm pretty sure that almost every other language with 
interfaces and a singly-rooted object hierarchy has implicit conversions 
from an interface to the base object type.  Oddly enough, an explicit 
cast "fixes" things:

     Object baz = cast(Object) foo;
     baz.toString(); // OK

What doesn't make sense is why the inline cast of foo is not allowed, 
even though it seems to me that it should have the exact same effect. 
Am I missing something here?

Dave


More information about the Digitalmars-d-learn mailing list