D's constructor call hierarchy (Was: Re: [Bug 91] Inherited classes require base class to have a default constructor.)
Søren J. Løvborg
web at kwi.dk
Sun Apr 9 04:51:50 PDT 2006
Bruno Medeiros wrote:
> If the derived class initializing is the same as the base class, I
> shouldn't have to repeat myself. For that code (MyException) I have to do
> the following, which is redundant:
>
> class MyException : Exception {
> this(char[] msg) {
> super(msg);
> }
> }
I think there's a valid point here, namely that one shouldn't be forced to
type boiler-plate code like this -- for the same reason, many IDEs can
generate declarations like this automatically.
Constructors are not methods, and thus aren't inherited (since neither D nor
C++ have the notion of virtual constructors), and of course it should be
possible to prevent instantiation of subclasses using superclass
constructors, for obvious reasons.
But I've never understood why, if no constructors are defined explicitly,
only the zero-argument constructor is automatically defined ("inherited" if
you will), and not _all_ of the superclass constructors.
Take for instance a subclass of Error. Error itself defines two constructors
(one taking a message, and one additionally taking another Error, for
exception chaining), and a subclass might want to do the same.
With a constructor-less definition like
class MyError : Error { }
I don't see why both of Error's constructors could not implicitly be
defined.
Of course, if one specified one or more constructors, no implicit
constructors should be defined.
(On an unrelated note, shouldn't Exception also support exception chaining?)
--
Søren J. Løvborg
web at kwi.dk
More information about the Digitalmars-d
mailing list