3

According to this page

http://www.delphibasics.co.uk/RTL.asp?Name=Inherited

It says "It is called at the start of a constructor, and at the end of a desctructor. It is not mandatory, but recommended as good practice. "

Did I not understand correctly this? Does it mean that we don't need to put 'inherited' in constructor or destructor because it will be automatically inserted by compiler?

justyy
  • 5,831
  • 4
  • 40
  • 73
  • 1
    To perhaps address the crux of the ambiguity, the quoted sentence is saying that placing `inherited` first (in a constructor) or last (in a destructor) is not mandatory - technically you can put your own code before and after calls to `inherited`, it's just that most of the time this is not a very good idea. – J... Jun 29 '13 at 18:18

2 Answers2

11

No, inherited isn't called automatically; you have to do it yourself (if you want to call the inherited procedure, which you normally do). And you can even choose when to do it, see, e.g., this answer. Typically you do it at the beginning of a constructor, and at the end of a destructor.

Community
  • 1
  • 1
Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
9

No, that's not what it means; what it's saying is that you can choose not to call it if you have a reason not to call it. You should almost always call inherited in every method you're overriding, unless you need for something not to happen in your descendant that the parent does.

Unless you have a very good reason not to do so, you should always call inherited as the first line of your constructor, and the last line of your destructor. It is never called automatically.

Delphi makes it very easy; if your overridden method has the same parameters as the parents, you don't even have to pass them on:

constructor TMyClass.Create(AOwner: TComponent);
begin
  inherited;          // Automatically passes AOwner to parent constructor
  // Do other construction here
end;

destructor TMyClass.Destroy;
begin
  // Do your own cleanup
  inherited;
end;
Ken White
  • 123,280
  • 14
  • 225
  • 444
  • I think this is clearer than the accepted answer. +1. There are conceivable (rare) cases to NOT call it, and doing so intentionally probably deserves "do not call inherited" comment, because some tools like the Pascal Analyzer from peganza will issue warnings, and it's even possible the Delphi compiler might emit a hint or warning. – Warren P Jun 30 '13 at 21:56