Programs often need to maintain a linked list of records. Each record then contains a pointer to the next record (and possibly to the previous record as well). For type safety, it is best to de ne this pointer as a typed pointer, so the next record can be allocated on the heap using the New call. In order to do so, the record should be de ned something like this:
Type
TListItem = Record Data : Integer; Next : ^TListItem; end; |
When trying to compile this, the compiler will complain that the TListItem type is not yet de ned when it encounters the Next declaration: This is correct, as the de nition is still being parsed.
To be able to have the Next element as a typed pointer, a 'Forward type declaration' must be introduced:
Type
PListItem = ^TListItem; TListItem = Record Data : Integer; Next : PTListItem; end; |
When the compiler encounters a typed pointer declaration where the referenced type is not yet known, it postpones resolving the reference till later. The pointer de nition is a 'Forward type declaration'.
The referenced type should be introduced later in the same Type block. No other block may come between the de nition of the pointer type and the referenced type. Indeed, even the word Type itself may not re-appear: in e ect it would start a new type-block, causing the compiler to resolve all pending declarations in the current block.
In most cases, the de nition of the referenced type will follow immediatly after the de nition of the pointer type, as shown in the above listing. The forward de ned type can be used in any type de nition following its declaration.
Note that a forward type declaration is only possible with pointer types and classes, not with other types.