Overloading/Inheritance issue

Sean Kelly sean at f4.ca
Fri Aug 3 22:36:06 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.

Certain C++ compilers have done something like this in the past, if I 
remember correctly.  I'd have to do some googling to remember the 
details, but I'm sure it was either the MS or Sun compiler.


Sean



More information about the Digitalmars-d mailing list