Why can't static functions be virtual

Bill Baxter dnewsgroup at billbaxter.com
Tue Jan 16 22:21:38 PST 2007


Xinok wrote:
> Simply put, static functions don't have a 'this' pointer, so it's impossible to make a static function a virtual function.
> Objects with virtual functions have a 'hidden ID' which sets a unique value for each class type (AFAIK anyways...). If you don't have the 'this' pointer, you can't read the hidden ID in the object, so you don't know what type the object is, making it impossible to know which virtual function to call.

I think there is a usage case for a function that acts virtual when 
called with an object instance, but static when called with just the 
class name.

It almost seems like you should be able to achieve it by just defining 
two versions of the method:

     foo() { ... }
     static foo() { ... }

If you think of the non-static version as having a hidden 'this' 
parameter, those two are not ambiguous according to standard overloading 
rules.

On the other hand, you can pretty easily just make two versions of the 
function to achieve much the same thing, and just have the virtual 
version call the static version.

     static Foo() {}
     foo() { Foo(); }

Then if you have an object instance you can call inst.foo() and 
otherwise you can call Klass.Foo().

--bb



More information about the Digitalmars-d mailing list