Why can't static functions be virtual
John McAuley
john_mcauley at bigfoot.com
Tue Jan 16 15:52:28 PST 2007
I was going to ask why they weren't virtual.
I wrote this:
class CBase
{
static void hello()
{
printf("hello from CBase\n");
}
}
class CDerived : CBase
{
static void hello()
{
printf("hello from CDerived\n");
}
}
void main()
{
CDerived derived = new CDerived;
CBase base = derived;
base.hello(); // prints Hello from CBase
void function() fn;
fn = &CDerived.hello;
fn =&base.hello; // compiler error
}
Are statics non-virtual because that's the way c++ does it?
Surely the compiler can see base.hello() and then:
* look up the CBase class definition to find hello
* get its index in the vtable and note that it is static
* dereference base to get the CDerived vtable
* get the address that corresponds to hello
* call hello without passing base as a secret this pointer
Its the same sequence of steps as for a non-static virtual. The only difference is that you don't pass base as a hidden parameter. The difference is how parameters are passed on the stack.
Then when the compiler sees:
fn = &base.hello;
It does the same vtable lookup and assigns the found address to fn because statics don't need the 'secret this pointer'.
I expected that &base.hello would be equivalent to &CDerived.hello
and that &derived.CBase.hello would be equivalent to &CBase.hello just as derived.CBase.hello() prints "Hello from CBase"
Anyway, the question is: why doesn't D do this? Why the distinction between static members and non-static members?
More information about the Digitalmars-d
mailing list