Skip to content

A matter of Class

Emp_Obj := <strong>TEmployee</strong>.Create(EditNameNew.Text,EditSurnameNew.Text);
...
// getEmployee(integer) gets the i-th pointer-to-employee of a TList object
getEmployee(i).Destroy; // the i-th employee object is destroyed

In comments of code the constructors are marked as class methods, while the destructor don't. What does it mean?
Simply, the first can be called directly from the class, while the second only from the specific object (which must be destroyed) because a class cannot be destroyed.

//Public Class Method (<strong>class</strong> becomes <strong>static</strong> in C++)
class function CountEmployees(): integer;
...
class function TEmployee.CountEmployees(): integer;
begin
  result := counter;
end;

Constructors are implicitly class methods, but not the only possible ones.
Every procedure/function you want to execute in a general way can be defined as class method, by preceding both of its definition and declaration with the class modifier: that's what we've done with the CountEmployees function.

Somebody could ask him/herself why to have a class method if any operation is inherent to the objects existence.
We have two major correlated reasons: some operations are generalizable or naturally independent from the specific class's instantiation, so by writing them as class methods we accelerate the computational cycles, making the software execution (a little bit) lighter.

Invoking a class method is referred as talking with a class.

Employee-Unit
Employee Unit

Now, where do we write our class?
We could insert it in the default unit file associated to the creation of form, in the first zone dedicated to types definition.
But it's better to keep an order modulating every file according to specific jobs: so we'll write it into another file which we'll associate to the project.

 

 

First of all, we create a new unit file by clicking on the icon bounded in red in picture beside, or File -> New Unit.

Add-File-To-Project
Add File To Project

Then we add the file save the file, preferably into your project's folder, with a name that could be Employee (.pas).After that we associate this file, which is on focus in the editor window, to the project.
We have two ways.

First, in this picture: from menu, Project -> Add editor file to Project (then confirm).

 

 

Project-Inspector
Project Inspector
Project-Inspector-Add
Project Inspector - Add
Add-Editor-File
Add Editor File

Second: from menu, Project -> Project Inspector.

Then, click on the button +.

Finally, Add editor files tab, and press OK.

 

(Employee.pas file is already selected; if not, do it)

Let's try to summarize the first main points when we write a class, or we read an old one.