* * *

Author Topic: [SOLVED] destructor and free procedure  (Read 180 times)

egsuh

  • Full Member
  • ***
  • Posts: 111
[SOLVED] destructor and free procedure
« on: July 10, 2018, 07:30:50 am »
I'm not sure why I'm coming back to the basics repeatedly.

When I'd like to clear objects within objects, should I use destructor or procedure Free?

Example is:

Code: Pascal  [Select]
  1. type
  2.   TMyObj = class
  3.       AStringList: TStringList;
  4.    
  5.       constructor Create;
  6.       procedure Free;             // 1.  Should I declare destructor or procedure?
  7.                                              // 2.  If I declare procedure, should I declare 'overide' to free?  
  8.    end;
  9.  
  10. ....
  11. implementation
  12.  
  13. procedure TMyObj.Free;
  14. begin
  15.      AStringList.Free;
  16.      inherited Destroy;      // 3.  Should I declare Destoy here?
  17. end;
  18.  

I know that any Object can be 'free'd without declaration as it is declared as TObject.Free.  What is the best if I want to do something before destruction? My three questions are within the example code.

« Last Edit: July 10, 2018, 08:31:13 am by egsuh »

taazz

  • Hero Member
  • *****
  • Posts: 5153
Re: destructor and free procedure
« Reply #1 on: July 10, 2018, 07:39:08 am »
To clean up after using an object you call free to clean a objects internal memory you override destroy.

PS:
  The keyword is override here if its not declared virtual or dynamic it can't be overridden.
« Last Edit: July 10, 2018, 08:00:33 am by taazz »
Good judgement is the result of experience … Experience is the result of bad judgement.

OS : Windows 7 64 bit
Laz: Lazarus 1.4.4 FPC 2.6.4 i386-win32-win32/win64

mangakissa

  • Hero Member
  • *****
  • Posts: 810
Re: destructor and free procedure
« Reply #2 on: July 10, 2018, 08:16:22 am »
destructor Destroy; override;

destructor Destroy;
begin
  AStringList.Free;
  inherited;
end;
Lazarus 1.64 (32b) / FPC 3.0
Windows 10

egsuh

  • Full Member
  • ***
  • Posts: 111
Re: destructor and free procedure
« Reply #3 on: July 10, 2018, 08:30:59 am »
Oh I see.

Thank you.  Actually I found I myself had done the same before.
I cannot add override to "free".  I should never write "procedure Free" myself.

 

Recent

Get Lazarus at SourceForge.net. Fast, secure and Free Open Source software downloads Open Hub project report for Lazarus