Why can't static functions be virtual

Bill Baxter dnewsgroup at billbaxter.com
Wed Jan 17 01:01:00 PST 2007


John McAuley wrote:
> 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? :-)
> 

The problem is that static methods generally don't have offsets in the 
vtable at all, so getting the CDerived vtable doesn't help.

--bb



More information about the Digitalmars-d mailing list