Why there are no 'physical' object variables (only references)?

BCS BCS at pathlink.com
Wed Sep 13 09:25:19 PDT 2006


Reiner Pope wrote:
> BCS wrote:
> 
[...]
>>
>> No, because the type of a struct is always known, the required value 
>> for the interface's function table can be found at compile time and 
>> all that is needed is to attach it to a reference to the struct.
> 
> I don't understand you. How would it work?
> 
> Suppose you had this code:
> 
> interface Foo
> {
>     int foo();
> }
> 
> struct Bar : Foo
> {
>     int foo() { ... }
>     ...
> }
> 


If I understand it correctly interfaces variables are a fat pointer, 
sort of like a delegate. They could be implemented something like this:

struct Interface
{
	void* context;
	void*[] v_table;
}

When a class implements an interface it creates a static array 
containing  pointers to it's methods. A reference to this array is 
placed in that classes v-table. When an interface instance is needed 
something like this is done:

class C : Foo {...}
C c = new C;
Interface i;

		// set context
i.context = c;
		// set v-table
i.v_table = c.vtbl[C.Foo_index];

When an interface is used to call a method it ends up looking something 
like this (omitting a bunch of casts):

i.v_table[Foo.foo_index](i.context);


The only reason that the v-table for the interface is referenced by way 
of the v-table of the class is that the actual type of the class isn't 
known until run time. For a struct, that isn't the case, the type is 
always known. Their for, something like this can be done.

Bar bar;

		// set context
i.context = &bar;
		// set v-table
i.v_table = Bar.Foo_vtbl];

this doesn't require any v-table in Foo

 > void calc(Foo f) { ... }
 >
 > How can calc know the type of every struct it is passed unless a
 > separate version of calc is generated for every type (in which case it
 > is just a template)?

a function that uses an interface NEVER knowns the type of the 
underlying data. In fact the only way it ever uses it is by passing it 
as a context to one of the function accessed by way of the v-table 
referenced in the /interface/

this is analogous to a function taking a delegate not caring what the 
context of that delegate is.

 >
 > Cheers,
 >
 > Reiner



More information about the Digitalmars-d mailing list