D's constructor call hierarchy (Was: Re: [Bug 91] Inherited classes require base class to have a default constructor.)
Bruno Medeiros
brunodomedeirosATgmail at SPAM.com
Sat Apr 8 17:17:39 PDT 2006
Sean Kelly wrote:
> Bruno Medeiros wrote:
>>
>> Ok, so the spec says:
>>
>> "If there is no constructor for a class, but there is a constructor
>> for the base class, a default constructor of the form:
>> this() { }
>> is implicitly generated."
>>
>> But why is this? Why must a derived class have it's own constructor,
>> explicit or not?
>
> As far as I know, all classes have an implicit this() ctor if no ctor is
> explicitly defined. Otherwise it would be impossible to instantiate the
> class.
It's not true (that "it would be impossible to instantiate the class."),
since for derived classes a super constructor could be used to
instantiate it.
>
> I don't think this makes sense. One time, I wanted to
>> create a new exception class, just to throw around and make use of
>> it's class type. So it didn't have any new content. I coded:
>>
>> class MyException : Exception { }
>>
>> ... and surprised I was when this didn't compile, as it isn't valid
>> code. (Because an implicit constructor "this() { }" is inserted, but
>> there isn't a super constructor with 0 parameters).
>
> A derived class is responsible for passing the appropriate parameters to
> its base class for initialization. This is done automatically when the
> base class has no explicit ctor or has a zero-parameter ctor, but
> otherwise you have to do this explicitly.
>
> Seems to me this
>> idea of inserting an implicit default constructor doesn't make sense,
>> yet both Java and C# have this behavior (and C++ for what was said),
>> so can it be I'm missing something? :/
>
> C++ has this behavior as well. In fact, a default ctor, copy ctor, and
> assignment operator are all generated if no ctor or assignment operator
> are explicitly defined.
>
>
> Sean
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);
}
}
also, this reuse has to be done for all super constructors that one
wants to be available on the derived class. And... hum...
Damn...
I've just answered myself. This design allows "one to hide superclass
ctors", just like kris said, but only now did I get it. I guess that's
the reason why the new languages have that behavior? Hum, what's it like
in non-C-family OO languages like Ruby and Python, anyone knows ?
(Also, DMD could print a better message when an inserted implicit
super() is not found.)
--
Bruno Medeiros - CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D
More information about the Digitalmars-d
mailing list