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 12:37:02 PDT 2006


d-bugmail at puremagic.com wrote:
> http://d.puremagic.com/bugzilla/show_bug.cgi?id=91
> 
> 
> ------- Comment #3 from smjg at iname.com  2006-04-07 11:55 -------
> Yes, including C++ and Java.  If anybody could circumvent the requirement to
> use a constructor simply by creating a derived a class, it would defeat the
> point.
> 
> You can, however, put a protected constructor in the base class.  This is a
> constructor created specifically for derived classes to base their constructors
> on.  You would be able to completely override* a constructor if the base class
> has a protected constructor that does nothing.  But can you think of an example
> in which this would make sense?
> 
> * Actually, constructors don't override as such.  A constructor is a member
> only of the class in which it is defined, not of any derived classes.  Hence if
> the base class has no default constructor, then when deriving a class from it
> you must explicitly define a constructor.
> 
> 

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? 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). 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? :/

-- 
Bruno Medeiros - CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D



More information about the Digitalmars-d mailing list