Why can't static functions be virtual

Daniel Keep daniel.keep+lists at gmail.com
Tue Jan 16 20:06:57 PST 2007


I suppose it does it this way because every other statically typed 
language I know of does it this way.  And they do it because, AFAIK, it 
makes sense to.  The method you are calling isn't attached to the 
instance at all--it's attached to the class itself.

When you say "base.hello()", the compiler's actually cutting you some 
slack and saying "well, I know what you *really* mean, so I'll let you 
off" and calls the method.

class Foo { static void bar() { ... } }

is pretty much the same as

void Foo_bar() { with(Foo) { ... } }

Which means that "base" has absolutely nothing to do with looking up the 
method whatsoever (well, apart from what the container type is).

Look at it like this: static methods don't HAVE a vtable; they're just 
methods that sit somewhere in memory that just happen to be related to a 
certain class.  There's simply no mechanism for looking up derived 
versions at runtime.

So yeah; this same thing caught me once or twice when I first started 
with C++, but I've honestly never been able to come up with a compelling 
reason to do it any other way.

	-- Daniel



More information about the Digitalmars-d mailing list