Order of base-class constructor calls

Andrej Mitrovic andrej.mitrovich at gmail.com
Fri Oct 7 15:02:33 PDT 2011


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.


More information about the Digitalmars-d-learn mailing list