Pages

Friday 9 November 2012

Constructors and Destructors in Delphi Programming Language

Constructors and Destructors in Delphi Programming Language

This article provides you the basic syntax of constructors and destructors in delphi programming language with explanation.

Constructors:

All objects in Delphi have a standard constructor ("Create"), which they get from TObject.

type
  TSomething = class(TObject)
  public
    { Public declarations }
    constructor Create;
    //your delphi code
  end;

implementation
//this is your actual constructor definition
constructor TSomething.Create;
begin
  inherited;
  //do whatever you need (allocate memory, initialize variables, etc.)
end;

Destructors:

type
  TSomething = class(TObject)
  public
    destructor Destroy; override;
  end;

implementation
destructor TSomething.Destroy;
begin
  //do any cleaning up necessary here
  inherited;
end;

Explanation of Constructors and Destructors in Delphi

This code should give you a full sense of familiarity, as it's almost the same as the constructor code. There's only one difference - "override". This is because the standard Destroy destructor is declared as Virtual.

Inherited: Since every class is a sub-class of TObject, they automatically get its properties, methods, events, etc. This includes the standard constructors and destructors ("Create" and "Destroy").

Since we have added our own code for the TSomething constructor the other code won't get executed - if you create a TSomething then TSomething.Create will get called, not TObject.Create.

This is bad, as the base class might be doing clever/important things. Using the "inherited" keyword lets you call the base class's same method. This works for any constructor/destructor/procedure/function ("method").

TObject: Every class is a sub-class of TObject, they automatically get its properties, methods, events, etc.

No comments:

Post a Comment