Inheritance of purity

Timon Gehr timon.gehr at
Fri Feb 17 05:33:15 PST 2012

On 02/17/2012 08:34 AM, Andrei Alexandrescu wrote:
> On 2/16/12 8:49 PM, Walter Bright wrote:
>> Given:
>> class A { void foo() { } }
>> class B : A { override pure void foo() { } }
>> This works great, because is covariant with, meaning it can
>> "tighten", or place more restrictions, on foo. But:
>> class A { pure void foo() { } }
>> class B : A { override void foo() { } }
>> fails, because tries to loosen the requirements, and so is not
>> covariant.
>> Where this gets annoying is when the qualifiers on the base class
>> function have to be repeated on all its overrides. I ran headlong into
>> this when experimenting with making the member functions of class Object
>> pure.
>> So it occurred to me that an overriding function could *inherit* the
>> qualifiers from the overridden function. The qualifiers of the
>> overriding function would be the "tightest" of its explicit qualifiers
>> and its overridden function qualifiers. It turns out that most functions
>> are naturally pure, so this greatly eases things and eliminates annoying
>> typing.
>> I want do to this for @safe, pure, nothrow, and even const.
>> I think it is semantically sound, as well. The overriding function body
>> will be semantically checked against this tightest set of qualifiers.
>> What do you think?
> I thought about this for a while and seems to work well. The maintenance
> scenarios have already been discussed (people add or remove some
> attribute or qualifier) and I don't see ways in which things become
> inadvertently broken.

I imagine that some contrived example could be deduced that uses 
__traits(compiles, ...) inside a pure function. But I don't think 
avoiding such scenarios is worthwhile.

> The const qualifier is a bit different because it allows overloading.
> Attention must be paid there so only the appropriate overload is
> overridden.

Introducing a new overload against const in a subclass is illegal:

class C{
     void foo(){}
class D : C{
     override void foo(){}
     override void foo()const{}

Error: multiple overrides of same function

> Congratulations Walter for a great idea. Inference is definitely the way
> to go.
> Andrei

More information about the Digitalmars-d mailing list