[fpc-pascal]Classes/Objects/Pointers / Pointer Help

Anton Tichawa anton.tichawa at chello.at
Mon Feb 10 16:28:21 CET 2003


Hello, James!

> Yes ok, fair enough, this much is in my knowledge of Pascal :) hehe, but
> the real question is, how do you create these objects on the fly in a
> program, ie: dynamic array...

The object TmyObject from our previous example uses no space at all. If your 
object contains fields, you might declare it statically, as in TmyObject, but 
"on the fly" requires dynamic allocation on the heap:

*** example 2
type t_my_object = object
  f_name: shortstring;
  procedure draw;
  end;

type p_my_objects = ^ t_my_object;

function allocate_my_objects (n: cardinal): p_my_objects;
begin
  getmem(result, n * sizeof(t_my_object));
end;

procedure main;
const
  num = 3;
var
  i: integer;
  p: p_my_objects;
begin
  p := allocate_my_objects (num);
  for i := 0 to num - 1 do begin
    p[i].f_name := 'instance ' + intstr(i);  // C-like syntax
  end;
  for i := 0 to num - 1 do begin
    p[i].draw;
  end;
  freemem(p);  // the memory manager knows where and how much to free
end.
***

I didn't actually compile and test this piece of code - there might be errors.

cheers - anton tichawa.


----------

"Adas Methode war, wie sich zeigen wird, Tagträume in offenbar korrekte 
Berechnungen einzuweben."

Doris Langley Moore: Ada, Countess of Lovelace (London 1977).

----------

Anton Tichawa
Volkertstrasse 19 / 20
A-1020 Wien
mobil: +43 664 52 07 907
email: anton.tichawa at chello.at

----------



More information about the fpc-pascal mailing list