Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a problem with both overriding a Delphi form constructor, _and_ using it's OnCreate event?

Delphi help says either override a form's constructor, or use the OnCreate event. But don't do both. What's the reason for this? The only thing I can see, is if inherited is left out of the constructor in a descendant, TCustomForm.Create won't get called. So OnCreate won't get called in that case. But if inherited isn't left out, I don't see the problem.

edit: I should add the reason for my question. I'm not actually planning to use both in the same class. But I was considering overriding the constructor in a base class, when a descendant is already using OnCreate. So I was wondering if there was some kind of conflict I wasn't aware of. But I'm getting the impression that should be ok. Although I may just use the OnCreate in the base class to keep it consistent.

another edit: Thanks everyone for the help. So it looks like using both methods won't actually break anything, if you do it correctly. But the problem with doing it, is that it makes the code hard to understand. And I guess I'm supposed to pick a best answer, but everyone seems to be in agreement. So I'll just pick the one that was posted first.

like image 249
user345464562354345345345.3 Avatar asked Apr 21 '11 09:04

user345464562354345345345.3


3 Answers

Both will get called. The advice is sound though since using both is confusing to readers of the code.

like image 50
David Heffernan Avatar answered Oct 05 '22 08:10

David Heffernan


Considering your edit, no there is no problem in using them both.

Just make sure you write your overriden constructor like so:

constructor TMyForm.Create(AOwner: TControl);
begin
  inherited;
  ....
  your new code here
end;

Also note that the OnCreate handler will be called before your added Create code so be aware of that. This can get confusing fast, that's why the manual recommends against it.

Warning

If you override a class do not use OnCreate, because that might block users of the OnCreate event from acting on that, just do your thing in the overriden constructor. The rule is that stuff that needs to the same in the Create of every instance of TMyForm should go into an override constructor.

Create stuff that can be different depending on where the TMyForm is used should go into the OnCreate Handler.

If there are any dependencies with other components nearby, then your code should always go into the OnCreate handler.

like image 31
Johan Avatar answered Oct 05 '22 08:10

Johan


You may end up placing identical - or comflicting - code in two different places. I almost always use the OnCreate event myself.

like image 43
Bob Swart Avatar answered Oct 05 '22 08:10

Bob Swart