Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Delphi allow constructor parameters to be incorrect?

Tags:

delphi

This might seem like a really silly question, but I don't know why this is even allowed to compile:

program ConstructorWithParam;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

type

  TThing = class(TObject)
  private
    FParent: TObject;
  public
    constructor Create(const AParent: TObject);
  end;

{ TThing }

constructor TThing.Create; // <- WTF? Why does the compiler not complain?
begin
  FParent := AParent;
end;

var
  Thing: TThing;
begin
  try
    Thing := TThing.Create(TObject.Create);
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

I'm using Delphi XE5 and have not tested on other versions. Thanks.

like image 944
Rick Wheeler Avatar asked Sep 03 '15 03:09

Rick Wheeler


1 Answers

The first declaration in the form class is presumed to be the correct one. The implementation version does not need to identify the parameters required; they're assumed by the original declaration. This is a part of the language itself.

Here's a good example to illustrate the point:

type
  TMyClass = class (Tobject)
    procedure DoSometimg(DoA, DoB: Boolean);
  end;

Implementation:

procedure TMyClass.DoSomething;   // Note both parameters missing
begin
  if DoA then    // Note not mentioned in implementation declaration
    DoOneThing;   // but still can be used here
  if DoB then
    DoAnotherThing;
end;

I personally prefer to make both the implementation and interface declarations match, because it makes it easier to identify the parameters without jumping around as much in the code editor.

like image 132
Ken White Avatar answered Nov 02 '22 23:11

Ken White