Why can't static functions be virtual
John McAuley
john_mcauley at bigfoot.com
Wed Jan 17 03:27:12 PST 2007
Bill Baxter Wrote:
>
> Seems like it should be possible for the compiler to realize when you're
> not using 'this' in a method and create the vtable entry for the
> function sans hidden 'this' parameter. Then it could make such a
> function callable via either Class.method or instance.method syntax.
>
> --bb
Pretty much.
Though I don't think that this pointers appear anywhere in the vtable. I suspect that the vtable is a plain old fashioned array of addresses living somewhere in read only memory. One address per func, just 1s and zeros.
The compiler would have written references, resolved by the linker, fixed up to absolute addresses by the OS's app/module loader.
The this pointer will probably be passed to instance funcs via the stack frame.
You write:
class CFoo
{
int m_i;
void func() { m_i = 2; }
}
the compiler emits:
void name_mangled_func(CFoo sneakyThis)
{
sneakyThis.m_i = 2;
}
and:
foo.func() is emited as:
func_address = find_address_of_func(foo, funcIndex)
func_address(foo)
I don't know exactly what the d compiler is doing but I suspect that its something like the above. find_address_of_func is probably inline pointer dereferencing.
Soooo... for statics
class CFoo
{
static int s_i;
int m_i;
static void func()
{
s_i = 4;
}
}
the compiler emits:
void name_mangled_func()
{
// s_i is a single var somewhere in memory
// don't need this pointers to find it
//
s_i = 4;
}
and:
foo.func() is emited as:
func_address = find_address_of_func(foo, funcIndex)
func_address()
So, as you can see, its just the 'line' that calls the function that changes. func_address() instead of func_address(foo)
-Disclaimer
I don't actually KNOW what the d compiler is doing. This is all quesswork. It would be great if a d compiler expert could chip in to say if its possible or not from an implementation standpoint.
More information about the Digitalmars-d
mailing list