2021 = Virtual and Override

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

What is Virtual

A method declared with 'virtual' can be overriden in any derived classes.

So look at this section from the 'Piece' class:

class Piece
    {
        protected bool destroyed, belongsToPlayer1;
        protected int fuelCostOfMove, VPValue, connectionsToDestroy;
        protected string pieceType;

        public Piece(bool player1)
        {
            fuelCostOfMove = 1;
            belongsToPlayer1 = player1;
            destroyed = false;
            pieceType = "S";
            VPValue = 1;
            connectionsToDestroy = 2;
        }

        public virtual int GetVPs()
        {
            return VPValue;
        }

        public virtual bool GetBelongsToPlayer1()
        {
            return belongsToPlayer1;
        }

        public virtual int CheckMoveIsValid(int distanceBetweenTiles, string startTerrain, string endTerrain)
        {
            if (distanceBetweenTiles == 1)
            {
                if (startTerrain == "~" || endTerrain == "~")
                {
                    return fuelCostOfMove * 2;
                }
                else
                {
                    return fuelCostOfMove;
                }
            }
            return -1;
        }
    }

The methods 'GetVPs', 'GetBelongsToPlayer1', and 'CheckMoveIsValid are methods which can be overriden in any subclass.

So in the classes 'BarronPiece', 'LESSPiece', and 'PBDSPiece', 'CheckMoveIsValid' is overriden:

    class BaronPiece : Piece
    {
        public BaronPiece(bool player1)
            : base(player1)
        {
            pieceType = "B";
            VPValue = 10;
        }

        public override int CheckMoveIsValid(int distanceBetweenTiles, string startTerrain, string endTerrain)
        {
            if (distanceBetweenTiles == 1)
            {
                return fuelCostOfMove;
            }
            return -1;
        }
    }

So the classes 'BarronPiece', 'LESSPiece', and 'PBDSPiece' all have there own version of 'CheckMoveIsValid'.