how to fix such a hijacking problem in D ?

Bill Baxter dnewsgroup at billbaxter.com
Sun Dec 16 04:01:24 PST 2007


z_axis wrote:
> import std.stdio;
> 
> class A
> {
>     void foo(long) {}
>     void def() { writefln("A.def()"); foo(1L); }  // expects to call 
> A.foo(long)
> }
> 
> class B : A
> {
>     void foo(long) { writefln("B.foo()"); };    // will hijack A's foo()
> }
> 
> void abc(B b)
> {   
>     b.def();
> }
> 
> 
> void main(char[][] args)
> {   
>    abc(new B);
> }
> output:
> A.def()
> B.foo()
> 
> The B will hijack the A's foo(long) ?!
> 
> any suggestion ?


I think "final" is for that.  Says that the method should not be virtual 
(virtual is the default in D).

    final void foo(long) {...}

Not sure if that works, since it's actually not documented as far as I 
can tell.  But DFL uses 'final' a lot so I'd guess it does something. 
Or else DFL is just deluding itself.

Another option would be to rename them per-class, or use "static" if you 
don't actually need the 'this' pointer.

--bb


More information about the Digitalmars-d-learn mailing list