Overloading/Inheritance issue

Bruno Medeiros brunodomedeiros+spam at com.gmail
Sat Aug 4 03:42:18 PDT 2007


Walter Bright wrote:
> 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.

There is a problem the moment the D subclass doesn't override all 
overloads, so that can be detected at compile time and an error issued 
right there.


-- 
Bruno Medeiros - MSc in CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D



More information about the Digitalmars-d mailing list