[ACCEPTED]-Delphi/pascal: overloading a constructor with a different prototype-overloading

Accepted answer
Score: 32

There's a really easy way to avoid this. Give your new constructor a different name. Unlike 16 some other popular languages, Delphi has 15 named constructors; you don't have to call them Create. You 14 could call your new one CreateWithDataset 13 and not interfere with the virtual Create 12 constructor at all.

TfrmEndoscopistSearch = class(TForm)
  /// original constructor kept for compatibility
  constructor Create(AOwner: TComponent); override;
  /// additional constructor allows for a caller-defined base data set
  constructor CreateWithDataset(AOwner: TComponent; ADataSet: TDataSet; ACaption: string = '');
end;

In fact, unless you're 11 instantiating this class polymorphically, you 10 don't even need the original constructor. You 9 could declare your new one like this:

TfrmEndoscopistSearch = class(TForm)
  /// additional constructor allows for a caller-defined base data set
  constructor Create(AOwner: TComponent; ADataSet: TDataSet; ACaption: string = ''); reintroduce;
end;

Attempting 8 to call the one-argument constructor directly 7 on TfrmEndoscopistSearch would yield a compilation 6 error.


(Creating it polymorphically would 5 generally involve using Application.CreateForm:

Application.CreateForm(TfrmEndoscopistSearch, frmEndoscopistSearch);

That 4 always calls the one-argument virtual constructor 3 introduced in TComponent. Unless it's your 2 main form, you don't need to do that. I've 1 written about my feelings on Application.CreateForm before.)

Score: 19

Try adding reintroduce before the second overload, like this:

  TfrmEndoscopistSearch = class(TForm)
  public
    /// original constructor kept for compatibility
    constructor Create(AOwner : TComponent); overload; override;
    /// additional constructor allows for a caller-defined base data set
    constructor Create(AOwner : TComponent; ADataSet : TDataSet; ACaption : string = ''); reintroduce; overload;
  end;

This 3 compiles in Turbo Delphi. I needed the public to 2 make it compile because overloading of published methods 1 is restricted.

Score: 7
constructor Create(AOwner:Tcomponent;str:string);overload;
... 
constructor TfrmEndoscopistSearch.Create(AOwner: Tcomponent; str: string);
    begin
    inherited Create(AOwner);
    showmessage(str);
    end;

This should do the trick

0

More Related questions