Delphi/pascal: overloading a constructor with a different prototype

后端 未结 3 995
旧时难觅i
旧时难觅i 2020-12-29 06:21

I\'m trying to create a child class of TForm with

  1. a special constructor for certain cases, and
  2. a default constructor that will maintain compatibilit
3条回答
  •  梦毁少年i
    2020-12-29 06:23

    There's a really easy way to avoid this. Give your new constructor a different name. Unlike some other popular languages, Delphi has named constructors; you don't have to call them Create. You could call your new one CreateWithDataset and not interfere with the virtual Create 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 instantiating this class polymorphically, you don't even need the original constructor. You 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 to call the one-argument constructor directly on TfrmEndoscopistSearch would yield a compilation error.


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

    Application.CreateForm(TfrmEndoscopistSearch, frmEndoscopistSearch);
    

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

提交回复
热议问题