[fpc-pascal] Initialize object variables

Sven Barth pascaldragon at googlemail.com
Thu Apr 28 15:47:05 CEST 2011


Am 28.04.2011 11:33, schrieb Howard Page-Clark:
> On 28/4/11 10:00, Jürgen Hestermann wrote:
>>
>>
>> Darius Blaszyk schrieb:
>>> Is there any way to initialize object variables, other than writing an
>>> init method?
>>> So something like:
>>> myobj = object
>>> myvar: word = $ffff;
>>> end;
>> I don't think so.
>> An object is a pointer to a data structure on the heap.
>> At compile time, this data structure is not yet allocated.
>>
>> _______________________________________________
>> fpc-pascal maillist - fpc-pascal at lists.freepascal.org
>> http://lists.freepascal.org/mailman/listinfo/fpc-pascal
>>
> I think objects are allocated on the stack (not the heap), but that does
> not help in circumventing the init method to initialize them.

Yes, they are on the stack and yes that makes a difference:

=== source begin ===

type
   TMyObject = object
     i: Integer;
     s: String;
   end;

procedure Test;
var
   a: TMyObject = (
        i: 42;
        s: 'Foo';
begin
   Writeln(a.i);
   Writeln(a.s);
end;

=== source end ===

A call to "Test" will print

=== output begin ===
42
Foo
=== output end ===

This works with records (and primitive types) as well (it does not work 
in Delphi though as Delphi does not allow initialization of local variables)

Regards,
Sven



More information about the fpc-pascal mailing list