Is this a D puzzler or a bug?

Jarrett Billingsley kb3ctd2 at yahoo.com
Fri Mar 30 19:22:56 PDT 2007


"Chris Nicholson-Sauls" <ibisbasenji at gmail.com> wrote in message 
news:eukaln$h4q$1 at digitalmars.com...
>
> In trying to figure out an idea to put forward on how me might be able to 
> call super-class definitions directly (since the problem I see with 
> super.method() is that you can't selectively invoke a specific ancestor, 
> only your direct parent) I had the sudden cute thought about how it can be 
> done in MiniD (untested).  (Granted MiniD doesn't have 
> protection/visibility attributes, plus both inheritance and instantiation 
> behave differently from D, so its moot in that context, but the idea 
> stands conceptually.)
>
> class A {
>   function method () {}
> }
>
> class B : A {
>   function method () {
>     method(with this as A); // Its cute how existing syntax can read 
> sometimes.
>   }
> }

Nice shot (and very cute), but unfortunately because of the way global 
lookup works in MiniD, when you call "method(with this as A)" inside B's 
method(), it looks "method" up (and finds it) in 'this' first, calls itself, 
and so goes into infinite recursion.  Though you have just made me realize 
that there doesn't seem to be a way to call the base class's implementation 
of a method, directly or indirectly, in MiniD..!

>
> Thinking from here, the D equivelant would, I suppose, be this...
>
> class A {
>   protected void method () {}
> }
>
> class B : A {
>   override protected void method () {
>     (cast(A) this).method();
>   }
> }

If declared in separate files, this doesn't work.  If in the same file, this 
causes infinite recursion for much the same reasons as the MiniD code -- the 
method is looked up polymorphically, and so even though you're upcasting 
"this" to an A, it still calls the B implementation of method, and so it 
loops.

One thing that seems like it should work is:

typeof(super).method();

This compiles even if the classes are in separate files (while A.method() 
fails), but gives infinite recursion again.  Looking in the specs, it seems 
the "non-virtual call" meaning is only applied to the 
"typeof(this).method()" form, so doing "typeof(super).method()" still does a 
virtual call.  And of course again, this only allows you to call direct 
ancestors.

But then, how often do you need to call the implementation of a method more 
than one level up? 




More information about the Digitalmars-d-learn mailing list