polymorphism: overloading vs. overriding

markus_kranz at gmx.net markus_kranz at gmx.net
Sun May 7 04:41:32 PDT 2006


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

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

Does 'overriding' in D does not mean the same as in Java?

Regards,
Markus





More information about the Digitalmars-d mailing list