Why can't static functions be virtual

Boris Kolar boris.kolar at globera.com
Wed Jan 17 03:45:24 PST 2007


== Quote from John McAuley (john_mcauley at bigfoot.com)'s article
> 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.
> That doesn't sound right.
> For example:
>    CBase *baseRef = new CDerived;
>    baseRef.hello(); // hello is a virtual static
> I HAVE an object reference/pointer, its baseRef.
> The compiler knows the definition of the CBase class. So it knows the vtable
offset and the fact that hello is static.
> The compiler can emit code that dereferences baseRef to get the CDerived vtable,
gets the function address and calls it without passing baseRef as the 'hidden this
pointer'. The code calls the func as a static member and not as an instance member.
> Voila! virtual static call.
> Have I missed something? Should I slink away all embarrassed? :-)

If it worked the way you describe, it would be a little bit slower. The way it
works now,
compiler doesn't need to use object reference/pointer at all. It works just as if
you would
type "CBase.hello()" (and note that "." does not mean hello is invoked on an
instance, it's
just as if "CBase.hello" was a name of a global function).



More information about the Digitalmars-d mailing list