Overloading/Inheritance issue

Kirk McDonald kirklin.mcdonald at gmail.com
Wed Aug 1 14:20:44 PDT 2007


Chris Nicholson-Sauls wrote:
> Steve Schveighoffer wrote:
> 
>> Hi,
>>
>> I am wondering if the following behavior is intentional and if so, 
>> why.  Given the code below:
>>
>> class X
>> {
>>   public int foo()
>>   {
>>     return foo(0);
>>   }
>>
>>   public int foo(int y)
>>   {
>>     return 2;
>>   }
>> }
>>
>> class Y : X
>> {
>>   public int foo(int y)
>>   {
>>     return 3;
>>   }
>> }
>>
>> int main(char [][] argv)
>> {
>>   Y y = new Y;
>>   y.foo(); //does not compile, says that the argument type doesn't match
>>   y.foo(1);
>>   X x = y;
>>   x.foo();
>>   return 0;
>> }
>>
>>
>> How come the marked line above does not compile?  Clearly there is no 
>> ambiguity that I want to call the base's foo, which in turn should 
>> call Y's foo(int) with an argument of 0.  It's not that the method is 
>> not accessible, because I can clearly access it by casting to an X 
>> type (as I have done in the subsequent lines).
>>
>> If you interpret the code, I'm defining a default behavior for foo() 
>> with no arguments.  A derived class which wants to keep the default 
>> behavior of foo() as calling foo(0), should only need to override 
>> foo(int).  However, the compiler does not allow this.  Why?  Is there 
>> a workaround (besides implementing a stub function which calls 
>> super.foo())?  Maybe there is a different method of defining in a base 
>> class one version of a function in terms of another?
>>
>> -Steve
> 
> 
> I've never really 100% understood why this is the way that it is, but 
> there /does/ exist a simple workaround.  Add this line to Y:
>   alias super.foo foo;
> 
> Yep, alias the superclass's method into the current class's scope.  The 
> problem has something to do with the lookup rules.  At the very least, I 
> would think that declaring Y.foo with the 'override' attribute might 
> give the wanted behavior, since surely a int(int) couldn't override a 
> int(), yes?  But no, last I checked, it doesn't work either.
> 
> -- Chris Nicholson-Sauls

That's not a workaround, nor is this considered a problem. This is the 
intended behavior.

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org



More information about the Digitalmars-d mailing list