Why is Destroy not called?

Given the following Delphi code, Foothere is Free'd on FormClose, but TFoo.Destroynot called - and therefore Barnot Free' d, which leads to a memory leak

Am I missing something here or shouldn't Foo.Free call Foo.Destroy at some point?

type
  TBar = class
  SomeInteger : integer;
end;

TFoo = class
  Bar : TBar;

  constructor Create();
  destructor Destroy();
end;

var
  Foo : TFoo;

implementation

constructor TFoo.Create;
begin
  Bar := TBar.Create;
  Bar.SomeInteger := 2;
end;

destructor TFoo.Destroy;
begin
  Bar.Free;
  Bar := nil;

  showmessage('Destroyed!');
end;

procedure TForm10.FormCreate(Sender: TObject);
begin
  Foo := TFoo.Create;

  showmessage('Foo created');
end;

procedure TForm10.FormDestroy(Sender: TObject);
begin
  Foo.Free;
  Foo := nil;
end;
+5
source share
2 answers

You must mark the destructor's signature with an override.

destructor Destroy(); override;

And you must have inheriteda destructor at the end. But since your class is not derived from anything other than TObject, I suspect it doesn't matter.

+19
source

Destroy is virtual, and so you must override it in your descendant class.

TFoo = class
  Bar : TBar;

  constructor Create();
  destructor Destroy(); override; // must add override here
end;

, .

+8

All Articles