Interfaces allow member definitions?

Steven Schveighoffer schveiguy at yahoo.com
Thu Jan 30 10:16:21 PST 2014


On Thu, 30 Jan 2014 13:06:30 -0500, Frustrated <c1514843 at drdrb.com> wrote:

> On Thursday, 30 January 2014 at 17:38:26 UTC, Steven
> Schveighoffer wrote:
>> This is a misunderstanding, you still need to declare a class, because  
>> an interface is not a concrete type. But if there are default  
>> implementations for all the interface functions, you don't need to  
>> implement any of them!
>>
>
> No, the point is, if all methods are defined, there is no need to
> create the class. Why create an empty class to instantiate it
> when the compiler can do it for you and you can instantiate the
> interface? This is what I mean by treating the interface as a
> class because for all purposes it is. (an interface is just an
> abstract container but it doesn't have to be)
>
> Again, all this could be done by the compiler internally by
> creating a class to back an interface and add it to the vtable.
> Instantiating the interface just returns that class. Calling a
> member on the interface's object calls the member of that class,
> who's body is provided in the interface definition.
>
> I can do this now, the whole point is I don't like code
> duplication! ;)
>
> interface A
> {
>
>       void foo() { writeln("me"); }
>       void bar();
> }
>
> class _A  // created internally by compiler
> {
>       void foo() { writeln("me"); } // added by compiler copied
> from A
>       void bar() { assert(0, "error"); } // added by compiler
> }

http://dlang.org/phobos/std_typecons.html#.BlackHole

-Steve


More information about the Digitalmars-d-learn mailing list