Overloading/Inheritance issue

James Dennett jdennett at acm.org
Sat Aug 4 10:03:01 PDT 2007


Walter Bright wrote:
> Bruno Medeiros wrote:
>> Walter Bright wrote:
>>> 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.
>>
>> There is a problem the moment the D subclass doesn't override all
>> overloads, so that can be detected at compile time and an error issued
>> right there.
> 
> I'm not sure that's the right thing to do.

In general, overloading virtual functions in the first place
is a mistake: in practice it means that in order for a derived
class to implement consistent behavior it must override all of
them.  A hard error on overloading virtuals would be fair; the
fix is to have non-virtual overloads dispatching to a single
virtual which has the most general form, and provides a single
point of customization for derived classes.

This might not sit well with those who think that virtual is
a good default though.  I'm not one of them; I've never seen
problems caused by non-virtual as default, but plenty caused
by virtual as default (mostly relating to programmers not
thinking deeply enough about what contracts mean for virtual
functions, where it's necessary to specify both what the
default implementation guarantees, and what derived class
implementations must guarantee, including which other functions
on the same object can legitimately be called from overrides).

-- James




More information about the Digitalmars-d mailing list