polymorphism: overloading vs. overriding

Bruno Medeiros brunodomedeirosATgmail at SPAM.com
Sun May 7 05:06:44 PDT 2006


markus_kranz at gmx.net wrote:
> In article <e3kjf0$2q09$3 at digitaldaemon.com>, Bruno Medeiros says...
>> Markus Kranz wrote:
>>> [snip]
>>> --
>>> import std.stdio;
>>>
>>> class Foo {
>>> void doIt() { writefln("Foo.doIt()"); }
>>> void doIt(Foo that) { writefln("Foo.doIt(Foo)"); }
>>> }
>>>
>>> class Bar : Foo {
>>> //overrides Foo.doIt()
>>> void doIt() { writefln("Bar.doIt()"); }
>>>
>>> //overloads (inherited) Foo.doIt(Foo)
>>> void doIt(Bar that) { writefln("Bar.doIt(Bar)"); }
>>> }
>>>
>>> int main() {
>>> Foo foo = new Bar();
>>>
>>> foo.doIt();
>>> foo.doIt(foo);
>>> }
>> No, it's not unnatural. For a function to override another, the return 
>> type must be covariant, but the parameters must be contravariant.
>> It's quite natural to be this way, in fact, it's the only correct way 
>> (other than invariant parameters).
>> The reason why it is so, is because for a function to override another, 
>> it must handle all (or more) inputs than the previous function.
>> Consider, in your example, the following addition
>>
>>   class Baz : Foo { }
>>
>> Foo.doIt(Foo that) can handle an argument of type Baz, but
>> Bar.doIt(Bar that) cannot handle such an argument. Thus Bar.doIt doesn't 
>> override Foo.doIt
> 
> I see Bar.doIt(Bar) does not override Foo.doIt(Foo) given your definition of
> overriding.
> But given your szenario:
> 
> Bar bar = new Bar();
> Baz baz = new Baz();
> 
> bar.doIt(baz);
> 
> AFAIS should work perfectly (cause baz is a Baz and so a Foo and Bar inherits
> from Foo the function doIt(Foo))...
> 
> ...and does so in Java (but that's no argument <g>)
> ...but fails in D <hmpf>
> 
> test.d(23): function test.Bar.doIt () does not match argument types (Baz)
> test.d(23): cannot implicitly convert expression (baz) of type test.Baz to
> test.Bar
> 

In http://www.digitalmars.com/d/function.html , "Function Inheritance 
and Overriding" it is said:
"However, when doing overload resolution, the functions in the base 
class are not considered:"
If that is the ideal behavior, well, that I'm not sure...

> Of course what dmd says is true, but why can't it implicitly convert expression
> (baz) of type test.Baz to test.Foo?
> 

Even if you put a cast(Foo) on the argument, it won't compile, because 
it only considers the overloads (Bar.doIt) of the child class (Bar)
Once again, if that is the ideal behavior, I'm not sure...

> Does 'overriding' in D does not mean the same as in Java?
> 
It does. The difference in behavior from Java, is what I said above.

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



More information about the Digitalmars-d mailing list