Overloading/Inheritance issue
Walter Bright
newshound1 at digitalmars.com
Fri Aug 3 22:25:06 PDT 2007
Regan Heath wrote:
> In fact example 2 shows that we currently have the undesirable and buggy
> behaviour in the current D implementation, eg.
>
> import std.stdio;
>
> class B
> { long x;
> void set(long i) { writefln("B::set(long)"); x = i; }
> void set(int i) { writefln("B::set(int)"); x = i; }
> long squareIt() { writefln("B::squareit()"); return x * x; }
> }
> class D : B
> {
> long square;
> void set(long i) { writefln("D::set(long)"); B.set(i); square = x *
> x; }
> long squareIt() { writefln("D::squareit()"); return square; }
> }
>
> long foo(B b)
> {
> b.set(3);
> return b.squareIt();
> }
>
> void main()
> {
> writefln(foo(new D));
> }
>
> Output:
> B::set(int)
> D::squareit()
> 0
>
> In the above example the object is actually of type 'D' but the method
> is called from a reference to a 'B'. The result is a call to
> B::set(int), instead of D::set(long) and then D::squareit() which fails
> utterly.
>
> This is an 'obscure' bug because it is happening silently.
I agree that this example is a problem. There's no way to detect it at
compile time, so it should throw a runtime exception. The way to
accomplish that is to stuff D's vtbl[] entry for B.set(int) with a dummy
function that throws the exception.
More information about the Digitalmars-d
mailing list