Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2011-04

Initialize object variables

4 messages · 4 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Darius Blaszyk

Is there any way to initialize object variables, other than writing an init method?

So something like:

myobj = object
   myvar: word = $ffff;
end;

Regards, Darius

Reply by email

Jürgen Hestermann
to Darius Blaszyk
Show quoted text 6 lines
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.

Reply by email

Howard Page-Clark
to Jürgen Hestermann
Jürgen Hestermann wrote 17 lines
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 - 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.

Howard

Reply by email

Sven Barth
to Howard Page-Clark
Howard Page-Clark wrote 20 lines
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 - > 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

Reply by email