polymorphism: overloading vs. overriding

Mike Parker aldacron71 at yahoo.com
Sun May 7 03:28:10 PDT 2006


Markus Kranz wrote:
> Following the rule of last surprise: wouldn't it be desirable if the output of
> the following program would be:
> 
> Bar.doIt()
> Bar.doIt(Bar)
> 
> The actual output
> 
> Bar.doIt()
> Foo.doIt(Foo)
> 
> at least for me is a little bit surprising since the best matching function
> seems to be Bar.doIt(Bar).
> As overriding with covariant return types is supported it seems a bit unnatural
> to me that overriding with covariant arguments does not work.
> 
> Instead of doing overload resolution before virtual function resolution (what
> seems to be done now) an implementation of 'covariant arguments' theoretically
> could be as simple as reversing the order of resolution.
> 
> What do you think?

This line is the key:

Foo foo = new Bar();

foo is an instance of Foo, not an instance of Bar, so the appropriate 
method (Foo.doIt(Foo)) is being called. Java and C++ both have the same 
behavior. What you are suggesting is unintuitive. Not all Foos are Bars, 
but all Bars are Foos. If you want Bar.doIt to be called when you have a 
an instance of Foo, you have to downcast.



More information about the Digitalmars-d mailing list