Interfaces allow member definitions?

Steven Schveighoffer schveiguy at yahoo.com
Thu Jan 30 12:17:23 PST 2014


On Thu, 30 Jan 2014 14:58:42 -0500, Frustrated <c1514843 at drdrb.com> wrote:

> On Thursday, 30 January 2014 at 17:11:24 UTC, Steven
> Schveighoffer wrote:
>> On Thu, 30 Jan 2014 11:58:15 -0500, Frustrated <c1514843 at drdrb.com>  
>> wrote:
>>
>>
>>> Essentially what it boils down to is treating interfaces like
>>> classes that have no fields). To avoid the diamond problem simply
>>> always choose the method that is not from the interface(since it
>>> is "default"), which is done naturally with the vtable.
>>
>> It's simpler than that. A function is a block of code. A vtable entry  
>> points to a block of code. Just point the vtable entry at the block of  
>> code that is the default implementation.
>>
>> -Steve
>
> But what if you want to provide some default behavior? We are not
> dealing with abstract classes here.
>
> Since there is currently no way to do what I am saying no
> "solution" will be adequate unless it fulfills the behavior.
>
> (again, it's not like we can't accomplish basically the same
> thing, the point is mainly about simplification)
>
> The question was about if there was any innate reason why this
> type of behavior couldn't be accomplish using the vtable. I'm
> assuming there is none and it could easily be done? (the compiler
> just has to reserve the space and setup the pointers to the
> functions?)

The interface defines the vtable, the class contains a value for that  
vtable.

If you imagine an interface vtable like this:

interface A
{
    void foo();
}

=>

struct A_vtbl
{
    void function() foo;
}

Note the default value is NULL.

When you create a class that inherits, it's class info contains an A_vtbl:

class B : A
{
    void foo() {writeln("hi";}
}

=>

struct B_typeinfo
{
    A_vtbl a_interface = {&B.foo};
}

And when you call foo on an instance of A, it uses the vtable, knowing  
that the layout is A_vtbl.

(this is simplistic, the real thing is more complex to explain, it's  
somewhere on the docs).

What I'm saying is, if you give a default to the function foo, then our  
straw-man A_vtbl looks like this:

struct A_vtbl
{
    void function() foo = A.default_foo;
}

And when you create B_typeinfo, if you haven't defined foo, it just points  
at that default foo (of course, you have to fill in B.foo, and for that,  
you actually have to do a thunk to convert to the interface I think, but  
this is not hard).

But it's important to note that A does not define an instance of A_vtbl,  
just the layout! You still need a concrete class to get a vtable instance  
to point at.

-Steve


More information about the Digitalmars-d-learn mailing list