Chapter 6
Classes

In the Delphi approach to Object Oriented Programming, everything revolves around the concept of “Classes”. A class can be seen as a pointer to an object, or a pointer to a record, with methods associated with it.

The difference between objects and classes is mainly that an object is allocated on the stack, as an ordinary record would be, and that classes are always allocated on the heap. In the following example:

Var  
  A : TSomeObject; // an Object  
  B : TSomeClass;  // a Class

The main difference is that the variable A will take up as much space on the stack as the size of the object (TSomeObject). The variable B, on the other hand, will always take just the size of a pointer on the stack. The actual class data is on the heap.

From this, a second difference follows: a class must always be initialized through its constructor, whereas for an object, this is not necessary. Calling the constructor allocates the necessary memory on the heap for the class instance data.

Remark In earlier versions of Free Pascal it was necessary, in order to use classes, to put the objpas unit in the uses clause of a unit or program. This is no longer needed as of version 0.99.12. As of this version, the unit will be loaded automatically when the -MObjfpc or -MDelphi options are specified, or their corresponding directives are used:

{$mode objfpc}  
{$mode delphi}

In fact, the compiler will give a warning if it encounters the objpas unit in a uses clause.

 6.1 Class definitions
 6.2 Abstract and sealed classes
 6.3 Normal and static fields
  6.3.1 Normal fields/variables
  6.3.2 Class fields/variables
 6.4 Class instantiation
 6.5 Class destruction
 6.6 Methods
  6.6.1 Declaration
  6.6.2 Invocation
  6.6.3 Virtual methods
  6.6.4 Class methods
  6.6.5 Class constructors and destructors
  6.6.6 Static class methods
  6.6.7 Message methods
  6.6.8 Using inherited
 6.7 Properties
  6.7.1 Definition
  6.7.2 Indexed properties
  6.7.3 Array properties
  6.7.4 Default properties
  6.7.5 Published properties
  6.7.6 Storage information
  6.7.7 Overriding properties
 6.8 Class properties
 6.9 Nested types, constants and variables