inheritancexna

Game game and inheritance


One noob question. I often see those kind of things:

        public Constructor(Game game, string effectAssetName)
        : base(game)

I really can't understant the function of the second line. This called the base but for what? Doesn't the game already defined in the first line with Game game?


Solution

  • The "base" call determines which constructor to call on the superclass - e.g. without :base(game) the superclass will not get initialised (ok to be precise, that particular constructor will not run, but a parameterless constructor might if there is one available)

    Usually when you subclass the Game class you are adding your own functionality, but you still need the Game class to initalise and implement it's own functionality. You are essentially making the following calls

    MyGameObject.Constructor(game, effectAssetName) 
    

    and

    Game.Constructor(game);
    

    Further ( bad :) ) example

    class Fruit 
    {    
      private bool _hasPips;
    
      public Fruit(bool hasPips) 
      {
         _hasPips = hasPips;
      }
    }
    
    class Apple : Fruit 
    {
      private bool _isGreen;
    
      public Apple(bool isGreen, bool hasPips) : base(hasPips)
      {
        _isGreen = isGreen;
      }
    }
    

    When creating a new Apple, the call to base(hasPips) is made, without this the hasPips property of the Fruit superclass will never get set (actually in this case it's illegal to create a constructor on Apple without calling the base(bool) constructor on Fruit since there is no parameterless constructor on Fruit)