Delphi Clinic | C++Builder Gate | Training & Consultancy | Delphi Notes Weblog | Dr.Bob's Webshop |
|
Borland Delphi 4 features a number of Object Pascal language enhancements, as usual. In this article, I'll address special support for TObject (and hence all classes) namely the AfterConstruction and BeforeDestruction events.
Before & After
TObject has two new protected methods: AfterConstruction and BeforeDestruction (protected means that we can't call them directly, but we can inherite & override them from TObject and call them from descendant classes).
They're methods, but they will be called automatically, so all we need to do is derive from an existing object and override & implement these new methods ourselves (and don't forget to call the inherited method).
AfterConstruction is called automatically right after an object's constructor, and BeforeDestruction is called automatically right before an object's destructor.
Descendant classes can override these methods to perform actions that shouldn't (or couldn't - like in C++) occur in the constructor or destructor itself.
Just like Default Parameters, these two virtual methods were first introduced in Borland C++Builder 3, a few months ago. This was needed, since virtual methods are not "ready to be called" until after the constructor has been executed, and are no longer "ready to be called" when the destructor starts executing. So, to be able to call a virtual method when an object is constructing, we needed some kind of "OnAfterConstruction" event, and the same holds for the "OnBeforeDestruction" event.
program Delphi4; uses SysUtils, Dialogs; type TDelphi4 = class(TObject) constructor Create; virtual; procedure AfterConstruction; override; procedure BeforeDestruction; override; destructor Destroy; override; public Answer: Integer; end {TDelphi4}; constructor TDelphi4.Create; begin inherited Create; Answer := 21 end {Create}; procedure TDelphi4.AfterConstruction; { this method is called right after the constructor } begin inherited AfterConstruction; Answer := Answer + Answer // Answer should be 42 now end {AfterConstruction}; procedure TDelphi4.BeforeDestruction; { this method is called right before the destructor } begin Answer := Answer div 6; // Answer should be 7 now inherited BeforeDestruction end {BeforeDestruction}; destructor TDelphi4.Destroy; begin if Answer <> 7 then ShowMessage('Wrong Answer!'); inherited Destroy end {Destroy}; begin with TDelphi4.Create do try ShowMessage('The Answer is... ' + IntToStr(Answer)); finally Free end end.Adding the AfterConstruction and BeforeDestruction methods to Delphi 4 is important for component builders that are providing VCL components for both Delphi and C++Builder, to avoid problems with the described differences in constructor and destructor behavior (virtual methods!) between Delphi and C++Builder.