6

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.

1 Answer 1

8

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.

4
  • Thanks Ken, I've been using Delphi for 15 years and I did not know this! And I agree - I prefer the interface to match the implementation. I assume that the only time this does not hold true is when overloading methods? Sep 3, 2015 at 3:33
  • 2
    TurboPASCAL 5.0 introduced this. Sep 3, 2015 at 5:41
  • Note that the compiler will only allow this if no parameters are specified, if they are specified they must match or the compiler will complain. This was a language feature of Pascal that pre-dates Delphi.
    – Andy_D
    Sep 3, 2015 at 7:57
  • 2
    Is kinda obvious but is worth to say, this is not valid for overloaded methods. When a method is overloaded, you must specify the parameters in the implementation section, so the compiler can know which body belongs to which method. Sep 3, 2015 at 11:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.