subclass instance construction

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Fri Nov 5 03:25:06 PDT 2010


On Fri, 05 Nov 2010 10:54:11 +0100, spir wrote:

> Hello,
> 
> 
> I have a weird bug related to class instance construction. My guess is
> that it seems a superclass's this() is implicitely called (before the
> subclass's one, if any), even if overriden and without any use of
> "super". In my case, I have schematically:
> 
> === super class ===
> 	this() {
> 	    doThis();
> 	}
> === sub class ===
> 	this() {
> 	    doFirst();
> 	    doThis();
> 	}
> 
> All happens as if doThis was performed _before_ doFirst... and performed
> again after doFirst! At least, that's what debug output shows, and it
> would correctly explain the bug. Strange. How should I express what I
> mean?


This behaviour is by design.  If the superclass has a constructor, but 
you don't call it explicitly in the subclass constructor, the compiler 
inserts a call to super() at the beginning of the subclass constructor.

Why is this required?  Because the superclass needs to be properly 
constructed.  If you don't call any of the superclass' constructors, it 
is most likely left in an inconsistent state.

The solution is to call the superclass constructor explicitly, at the 
point where you want it to be called.  This will give you the desired 
result:

  // superclass
  this()
  {
      doThis();
  }

  // subclass
  this()
  {
      doFirst();
      super();   // Make sure doThis() is called after doFirst()
  }


-Lars


More information about the Digitalmars-d-learn mailing list