D's constructor call hierarchy (Was: Re: [Bug 91] Inherited classes require base class to have a default constructor.)

Sean Kelly sean at f4.ca
Sat Apr 8 13:29:41 PDT 2006


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.

  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



More information about the Digitalmars-d mailing list