next up previous contents index search.gif
Next: 4.4 Methods Up: 4. Objects Previous: 4.2 Fields


4.3 Constructors and destructors

As can be seen in the syntax diagram for an object declaration, Free Pascal supports constructors and destructors. You are responsible for calling the constructor and the destructor explicitly when using objects. The declaration of a constructor or destructor is as follows:

Constructors and destructors

\begin{syntdiag}\setlength {\sdmidskip}{.5em}\sffamily\sloppy \synt{constructor\...
...ation}
\synt{constructor\ header} \lit* ; \synt{subroutine\ block}\end{syntdiag}

\begin{syntdiag}\setlength {\sdmidskip}{.5em}\sffamily\sloppy \synt{destructor\ ...
...ration}
\synt{destructor\ header} \lit* ; \synt{subroutine\ block}\end{syntdiag}

\begin{syntdiag}\setlength {\sdmidskip}{.5em}\sffamily\sloppy \synt{constructor\...
...t{qualified\ method\ identifier} \) \synt{formal\ parameter\ list}\end{syntdiag}

\begin{syntdiag}\setlength {\sdmidskip}{.5em}\sffamily\sloppy \synt{desctructor\...
...t{qualified\ method\ identifier} \) \synt{formal\ parameter\ list}\end{syntdiag}
A constructor/destructor pair is required if you use virtual methods. In the declaration of the object type, you should use a simple identifier for the name of the constuctor or destructor. When you implement the constructor or destructor, you should use a qulified method identifier, i.e. an identifier of the form objectidentifier.methodidentifier. Free Pascal supports also the extended syntax of the New and Dispose procedures. In case you want to allocate a dynamic variable of an object type, you can specify the constructor's name in the call to New. The New is implemented as a function which returns a pointer to the instantiated object. Consider the following declarations:

Type
  TObj = object;
   Constructor init;
   ...
   end;
  Pobj = ^TObj;
Var PP : Pobj;
Then the following 3 calls are equivalent:

 pp := new (Pobj,Init);
and

  new(pp,init);
and also

  new (pp);
  pp^.init;
In the last case, the compiler will issue a warning that you should use the extended syntax of new and dispose to generate instances of an object. You can ignore this warning, but it's better programming practice to use the extended syntax to create instances of an object. Similarly, the Dispose procedure accepts the name of a destructor. The destructor will then be called, before removing the object from the heap. In view of the compiler warning remark, the now following Delphi approach may be considered a more natural way of object-oriented programming.

root
1999-06-10