5

When I create my custom Class in Delphi Application I use standard procedure:

TCustomClass = Class
 private
  var1,var2 : integer/string/Real/Boolean...
  procedure P1...
  function F1...
 public
  constructor Create;
end;

...

CustomClass := TCustomClass.create;

I want to know do I always have to also create Destructor procedure or are resources automatically free when application closes?

I always use Application as owner, rarely Self or Nil and I don't remember I saw anyone declaring Destructor on classes I saw on Internet, except for one when someone used pointers.

Is the logic behind destructor same in Delphi as in C++ as described in this question:

Should every class have a virtual destructor?

Thanks in advance.

EDIT1: As Free Consulting mentioned I forgot to say that one of the variables might be TBitmap type

Community
  • 1
  • 1
Tomislav Horvat
  • 163
  • 1
  • 8
  • 1
    Every class in Delphi already has a virtual destructor. The issue is whether or not you need to override it. Override it if your class needs to perform finalization for resources acquired by this class, that are not finalized by the super class. – David Heffernan Jun 01 '16 at 12:53
  • 1
    You should include the fact you are using TBitmap member in your question. – Free Consulting Jun 01 '16 at 14:05

1 Answers1

3

It only needs to have a destructor if you need to clean up something, like allocated memory. For example, if you have used TClassname.Create(...) in the constructor, you need to free in the destructor method.

Of course there can be many different reasons to need a destructor (all the way up to informing the user that his data is about to get wiped), but this is the most common one.

Craig
  • 1,874
  • 13
  • 41
Jur
  • 520
  • 2
  • 18
  • If I use Bitmap : TBitmap.create to initialize Tbitmap variable in that class do I have to call destructor? – Tomislav Horvat Jun 01 '16 at 12:29
  • You don't have to CALL the destuctor, that is done automatically; BUT the destructor should include Bitmap.Free – Jur Jun 01 '16 at 12:32
  • Sorry I ment to say do I have to declare Destructor in Class declaration. – Tomislav Horvat Jun 01 '16 at 12:34
  • 2
    if you have allocated the bitmap in the constructor, yes you must have a destructor including bitmap.free. If you don't, you create a memory leakage, which will lead to VERY angry users. – Jur Jun 01 '16 at 12:35
  • 1
    Destructors are only sometimes called automatically - usually if it's a TComponent derivative with a non-nil owner or if you are using interfaces. The rest of the time the destructor is called as a part of object.free – Matt Allwood Jun 01 '16 at 13:13