Search code examples
delphiinheritancedelphi-10.1-berlin

FormClose inheritance


I'm quite new to Delphi Programming (I'm using version Delphi 10.1 Berlin), and I'm trying to understand how inheritance works.

Let's say I have two forms that have to do the same action when closed. To avoid code duplication, my initial idea was to create a superclass, TFoobarForm, that inherits from TForm, and then create a procedure FormClose like this:

procedure TFoobarForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  { Some code }
end;

After that, I would like to create two forms, let's say TFooForm and TBarForm, that inherit from TFoobarForm. But I don't know if there's a way to make these new forms perform the superclass FormClose action without having to manually call the procedure from every class that inherits from it.

In the end, what I'm looking for is a way to avoid writing this:

procedure TFooForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  inherited FormClose(Sender, Action);
end;

for every subclass of TFoobarForm.


Solution

  • Have the base class override the virtual DoClose() method:

    type
      TFoobarForm = class(TForm)
      protected
        procedure DoClose(var Action: TCloseAction); override;
      end;
    
    procedure TFoobarForm.DoClose(var Action: TCloseAction);
    begin
      { Some code }
      // call inherited to trigger the OnClose event, if it is assigned...
    end;
    

    Then you don't need to assign an OnClose event handler in the derived classes at all (unless they really want to handle the event differently then the base class).