inheriting constructos

Don nospam at nospam.com
Mon Nov 30 07:55:32 PST 2009


Andrei Alexandrescu wrote:
> Don wrote:
>> Andrei Alexandrescu wrote:
>>> Walter and I just discussed the matter of inheriting constructors. 
>>> Our thought on the issue:
>>>
>>> a) If a class doesn't define any constructors and adds no fields, 
>>> inherit constructors. Example:
>>>
>>> class MyException : Exception {}
>>>
>>> b) If a class defines at least one constructor, do not inherit 
>>> constructors.
>>>
>>> c) If a class doesn't define any constructors but does add at least a 
>>> non-static field -> undecided.
>>>
>>> What do you think?
>>>
>>> Andrei
>>
>> I would add: "and the class does not define a class invariant".
>>
>> A constructor exists to establish the class invariant (even if that 
>> invariant is implicit). For (a), the old invariant will still be 
>> satisfied.
>> In the case (c) there is a chance that the invariant will not be 
>> appropriate. In (c), I suggest that it is valid to inherit 
>> constructors if and only if the new class is a simple aggregate of the 
>> old class, together with the new members (which may have invariants of 
>> their own).
>> If there's no constructor and no invariant, then either it's a simple 
>> aggregate, or it's a bug.
>>
>>
> 
> Good point. I do think of classes that add fields that don't mess up the 
> invariant though:
> 
> class MyException : Exception {
>     private int sysCode;
>     invariant() { assert(sysCode < 100); }
> }
> 
> If default initialization of the field puts it in a state that respects 
> the invariant, there isn't a problem.

Oh, that's an interesting one. If default initialization doesn't respect 
the invariant, the invariant is likely to catch it on first use anyway. 
So requiring no invariant probably wouldn't catch many bugs.

The fact that D does default initialization makes this whole issue much 
less perilous than in C++.

Returning to the original question:
Right now, constructors are inherited if they have no parameters. It's 
hard to see why the no-parameter case should be treated differently.



More information about the Digitalmars-d mailing list