Why can't static functions be virtual

John McAuley john_mcauley at bigfoot.com
Wed Jan 17 09:05:29 PST 2007


James Dennett Wrote:

> John McAuley wrote:
> > Bill Baxter Wrote:
> > 
> >> 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
> > 
> > Change the compiler to write the offsets.
> 
> And then what happens when one virtual static calls
> another?  There's no "this" pointer in the first,
> so it can't use virtual lookup to find the second,
> and so it suddenly uses non-virtual lookup as soon
> as we insert a trivial forwarding function.  Not
> good.  The idea of virtual dispatch is very much
> tied to there being an object; the idea of static
> methods is very much about there *not* being an
> object.  Attempts to make them meet in the middle
> cause unpleasant side-effects, and in my opinion
> aren't worthwhile.  This has been discussed in the
> context of C++ many times, and the issues are the
> same as with D in this case.  Even overloading
> static with non-static methods is somewhat
> problematic, and not because of implementation
> issues.
> 
> -- James

Is this what you mean?

   class Cbase
   {
      static bool isLessThanILike(int x)
      {
         return test(x);
      }
      static bool test(int x)
      {
         return x < 55;
      }
   }

   class CFoo : CBase
   {
      static bool test(int x)
      {
         return x < 2;
      }
   }

   CBase baseRef = new CFoo;

   if (baseRef.isLessThanILike(20))
   {
      printf("Well I never expected that!\n");
   }
   else
   {
      printf("Am I a god of programming or what?\n");
   }

I think I've cleverly made CFoo less discriminating by overriding test(). D finds CFoo's vtable, gets the address of CBase.isLessThanILike which contains a hard coded call to CBase.test.

Ouch!

OTOH

The call to test was visibly lacking in an object ref so 'of course' it wasn't virtual. 

But maybe we are so used to having 'invisible this pointers' around that we'd make that mistake quite often.



More information about the Digitalmars-d mailing list