Asserting that a base constructor is always called

Ali Çehreli acehreli at yahoo.com
Sat May 23 22:15:49 UTC 2020


On 5/23/20 3:04 PM, Tim wrote:
> I have a base class GameObject:
> 
> /// Base class of most objects in the game
> class GameObject{
>      this(){
>          world[layer] = this;
>      }
> 
>      abstract void update(){}
> 
>      void draw(){}
> }
> 
> I want to make sure that whenever a class inherits from this, the base 
> constructor is always called. Either that or have an assertion that 
> gives an error if it isn't called.
> 
> Thanks

Is it not already called? I tried the following and it seems to work:

import std.stdio;

GameObject[1] world;
enum layer = 0;

/// Base class of most objects in the game
class GameObject{
   this(){
     world[layer] = this;
     writeln("called");
   }

   abstract void update(){}

   void draw(){}
}

class A : GameObject {
   this(int i) {
     writeln(__FUNCTION__);
   }

   override void update() {
   }
}

void main() {
   auto a = new A(42);
}

Ali



More information about the Digitalmars-d-learn mailing list