Need I to put overload or override words after the constructor declaration in derived class?

前端 未结 4 1007
不思量自难忘°
不思量自难忘° 2021-02-09 03:03

I have a class hierarchy, this one:

type
TMatrix = class
    protected
      //...
    public
      constructor Create(Rows, Cols: Byte);
    //...
type
  TMinMa         


        
4条回答
  •  后悔当初
    2021-02-09 04:03

    As far as I know, there are two separate issues here:

    Making sure the child class' constructor calls the base class' constructor

    You'll have to explicitly call the base class' constructor:

    constructor TMinMatrix.Create(Rows, Cols: Byte);
    begin
       inherited;
       //...
    end;
    

    Making sure the child class' constructor overrides the base class' constructor

    You'll also have to make the child class' constructor override, and the base class' constructor virtual, to make sure the compiler sees the relation between the two. If you don't do that, the compiler will probably warn you that TMinMatrix's constructor is "hiding" TMatrix's constructor. So, the correct code would be:

    type
    TMatrix = class
        protected
          //...
        public
          constructor Create(Rows, Cols: Byte); virtual;    // <-- Added "virtual" here
          //...
    type
      TMinMatrix = class(TMatrix)
        private
          //...
        public
          constructor Create(Rows, Cols: Byte); override;   // <-- Added "override" here
          constructor CreateCopy(var that: TMinMatrix);
          destructor Destroy; override;                     // <-- Also make the destructor "override"!
      end;
    

    Note that you should also make your destructor override.

    Introducing a constructor with different parameters

    Note that you can only override a constructor with the same parameter list. If a child class needs a constructor with different parameters, and you want to prevent the base class' constructors from being called directly, you should write:

    type
    TMyMatrix = class(TMatrix)
    //...
    public
      constructor Create(Rows, Cols, InitialValue: Byte); reintroduce; virtual;
    //...
    end
    
    implementation
    
    constructor TMyMatrix.Create(Rows, Cols, InitialValue: Byte);
    begin
      inherited Create(Rows, Cols);   // <-- Explicitly give parameters here
      //...
    end;
    

    I hope this makes things more clear... Good luck!

提交回复
热议问题