Subsections


5. Objects

In this short chapter we give some technical things about objects. For instructions on how to use and declare objects, see the Reference guide.


5.1 Constructor and Destructor calls

When using objects that need virtual methods, the compiler uses two help procedures that are in the run-time library. They are called Help_Destructor and Help_Constructor, and they are written in assembly language. They are used to allocate the necessary memory if needed, and to insert the Virtual Method Table (VMT) pointer in the newly allocated object.

When the compiler encounters a call to an object's constructor, it sets up the stack frame for the call, and inserts a call to the Help_Constructor procedure before issuing the call to the real constructor. The helper procedure allocates the needed memory (if needed) and inserts the VMT pointer in the object. After that, the real constructor is called.

A call to Help_Destructor is inserted in every destructor declaration, just before the destructor's exit sequence.


5.2 Memory storage of objects

Objects are stored in memory just as ordinary records with an extra field : a pointer to the Virtual Method Table (VMT). This field is stored first, and all fields in the object are stored in the order they are declared. This field is initialized by the call to the object's Constructor method.

Remark: In earlier versions of Free Pascal, if the object you defined has no virtual methods, then a nil is stored in the VMT pointer. This ensured that the size of objects was equal, whether they have virtual methods or not. However, in the 0.99 versions of free pascal, this was changed for compatibility reasons. If an object doesn't have virtual methods, no pointer to a VMT is inserted.

The memory allocated looks as in table (ObjMem) .

Table: Object memory layout
Offset What
+0 Pointer to VMT.
+4 Data. All fields in the order the've been declared.
...  


5.3 The Virtual Method Table

The Virtual Method Table (VMT) for each object type consists of 2 check fields (containing the size of the data), a pointer to the object's ancestor's VMT (Nil if there is no ancestor), and then the pointers to all virtual methods. The VMT layout is illustrated in table (VMTMem) .

The VMT is constructed by the compiler. Every instance of an object receives a pointer to its VMT.


Table: Virtual Method Table memory layout
Offset What
+0 Size of object type data
+4 Minus the size of object type data. Enables determining of valid VMT pointers.
+8 Pointer to ancestor VMT, Nil if no ancestor available.
+12 Pointers to the virtual methods.
...  



root
2000-12-20