views:

1642

answers:

6

Does Delphi call inherited on overridden procedures if there is no explicit call in the code ie (inherited;), I have the following structure (from super to sub class)

TForm >> TBaseForm >> TAnyOtherForm

All the forms in the project will be derived from TBaseForm, as this will have all the standard set-up and destructive parts that are used for every form (security, validation ect).

TBaseForm has onCreate and onDestroy procedures with the code to do this, but if someone (ie me) forgot to add inherited to the onCreate on TAnyOtherForm would Delphi call it for me? I have found references on the web that say it is not required, but nowhere says if it gets called if it is omitted from the code.

Also if it does call inherited for me, when will it call it?

+14  A: 

No, if you leave the call to inherited away, it will not be called. Otherwise it would not be possible to override a method and totally ommit the parent version of it.

Ralph Rickenbach
+3  A: 

The inherited call has to be made explicitly. In general no language automatically calls the inherited function in equivalent situations (class constructors not included).

It is easy to forget to make the inherited call in a class constructor. In such a situation if a base class needs to initialize any data you have an access violation waiting to happen.

Perhaps you could override DoCreate and DoDestory in your TBaseForm class so you could ensure some code is executed regardless of the implementation of child classes.

// interface

TBaseForm = Class(TForm)
...
Protected
    Procedure DoCreate(Sender : TObject); Override;
End

// implementation

Procedure TBaseForm.DoCreate(Sender : TObject);
Begin
    // do work here

    // let parent call the OnCreate property  
    Inherited DoCreate(Sender);
End;
Frank
+3  A: 

It is worth mentioning that not calling inherited in Destroy of any object can cause memory leaks. There are tools available to check for this in your source code.

mj2008
+1  A: 

The inherited code is not called implicitly, as the others have indicated. You must call it explicitly. This gives you some useful flexibility. For instance, you might want to do some preprocessing code prior to the inherited code, then do some post processing code afterwards. This might look like:

procedure TMyCalcObject.SolveForX;
begin
  ResetCalcState;
  inherited SolveForX;
  PostProcessSolveForX;
end;
Jody Dawkins
A: 

No. That's the whole point of overriding.

JosephStyons
+2  A: 

Inherited must be explicitly called in descendant objects as well as in visual form inheritance. If you use class completion then it adds inherited automatically if you flagged the definition as override (but not for reintroduce). If you are using visual form inheritance then when you add a new event hander through the form editor then it will add inherited as well.

Jim McKeeth