Order of base-class constructor calls

Steven Schveighoffer schveiguy at yahoo.com
Tue Oct 11 08:28:02 PDT 2011


On Fri, 07 Oct 2011 18:02:33 -0400, Andrej Mitrovic  
<andrej.mitrovich at gmail.com> wrote:

> Is there any way to enforce the user to call the base-class ctor via
> super(), so it's the first statement in his class ctor? e.g.:
>
> class Base {
>     this(int) { }
> }
>
> class Derived : Base {
>     this(int x) {
>         super(x);
>         // user statements
>     }
> }
>
> The problem I'm having is that Base does some required initialization
> in its ctor, and Derived shouldn't be allowed to call any Base class
> methods (well, virtual methods) before calling the Base ctor.
>
> This is somewhat mitigated if I have a default constructor in the base
> class, e.g.:
>
> class Base {
>     this() { /* init section */ }
>     this(int) { this(); }
> }
>
> class Derived : Base {
>     this(int x) {
>         // Base class ctor automatically called *before* any other  
> statements
>         // user statements..
>     }
> }
>
> But this is only partially safe as the user could still call super()
> or super(int) after he's made some calls of his own, e.g.:
>
> class Base {
>     this() { /* init section */ }
>     this(int) { this(); }
>     void foo() { /* expects Base.this() having been already called */ }
> }
>
> class Derived : Base {
>     this(int x) {
>         foo();  // boom
>         super();  // or super(int);
>     }
> }
>
> So I'm looking for some techniques or tricks (or, dare I say, design
> patterns :x) you guys might have if you've ever ran into this kind of
> problem.

Maybe you can make the ctor private?  Then the derived class cannot call  
it directly, it needs to be implicit.

-Steve


More information about the Digitalmars-d-learn mailing list