Base Class Hitting Derived Class Invariant

Vijay Nayar madric at gmail.com
Sun Nov 11 19:32:51 PST 2012


I was working on a little project when I encountered something 
odd.  Essentially a base class contains some data and a derived 
class needs a slice of that data.  Certain properties of this 
slice must be maintained, so the derived class has an invariant.

What happens is that if the base class, even in the constructor, 
calls a function that is overridden in the derived class, the 
invariant gets invoked.  This can make initialization quite 
difficult.

Below is a stripped down example of this.

void main() {
   auto b = new B([1, 2, 3, 4, 5, 6]);
}

class A {
   uint[] data;
   this(uint[] data) {
     this.data = data;
     init();  // This ends up calling B.init() and fails the 
invariant!
   }

   void init() {
     // Do some checking.
   }
}

class B : A {
   uint[] dataSlice;

   invariant() {
     assert(dataSlice !is null);
   }

   this(uint[] data) {
     super(data);
     dataSlice = data[3..$];
   }

   override void init() {
     // Do more checking;
     super.init();
   }
}

If the base class constructor needs to occur before the derived 
class constructor, is there a good way to solve this without 
getting rid of the invariant?

  - Vijay


More information about the Digitalmars-d-learn mailing list