Recent

Author Topic: array of objects or array of pointers?  (Read 2059 times)

anonymousstranger

  • New Member
  • *
  • Posts: 49
array of objects or array of pointers?
« on: February 01, 2021, 12:05:29 pm »
given:

Code: Pascal  [Select][+][-]
  1. type
  2. aclass= class(Tobject)
  3. var
  4.   data:integer;
  5.  
  6.   constuctor create; overload;
  7.   destructor destroy; overwrite;  
  8. end;
  9.  
  10. clarray=array of aclass;
  11.  
  12. var
  13.   myarraya:clarray;
  14.   myarrayb:clarray;
  15.   x:integer;
  16.  
  17. constructor aclass.create;
  18. begin
  19. inherited;
  20. end;
  21.  
  22. destructor aclass.destroy; overwrite;
  23. begin
  24. inherited;
  25. end;
  26.  
  27. function arraya(n:integer):clarray;
  28. var
  29.   k:integer;
  30.  
  31. begin
  32.   size(result,n);
  33.   for k:=0 to (n-1) do
  34.     result[k]:=aclass.create;
  35. end;
  36.  
  37. function arrayb(n:integer):clarray;
  38. var
  39.   k:integer;
  40.   myclass:aclass:
  41.  
  42. begin
  43.   size(result,n);
  44.   for k:=0 to (n-1) do
  45.     begin
  46.       myclass:=aclass.create;
  47.       result[k]:=myclass;
  48.       myclass:=nil;
  49.     end;
  50. end;
  51.  
  52. begin {main}
  53.   x:=3;
  54.   myarraya:=arraya(x);
  55.   myarrayb:=arrayb(x);
  56. end;
  57.  
  58.  


Is myarraya an array of objects, while myarrayb is an array of pointers to objects? Or are myarraya and myarrayb both arrays of objects, or both arrays of pointers to objects?

MarkMLl

  • Hero Member
  • *****
  • Posts: 8334
Re: array of objects or array of pointers?
« Reply #1 on: February 01, 2021, 12:18:10 pm »
An object is represented by a pointer which is automagically dereferenced to storage on the heap.

MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Logitech, TopSpeed & FTL Modula-2 on bare metal (Z80, '286 protected mode).
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

anonymousstranger

  • New Member
  • *
  • Posts: 49
Re: array of objects or array of pointers?
« Reply #2 on: February 01, 2021, 12:25:23 pm »
So these two arrays are the same?

egsuh

  • Hero Member
  • *****
  • Posts: 1563
Re: array of objects or array of pointers?
« Reply #3 on: February 01, 2021, 12:38:07 pm »
Quote
So these two arrays are the same?

Yes.

Class variable (MyClass of function arrayb in your example) contains pointer to the class object, while an integer variable contains integer. 

MyArrayA and MyArrayB are array of class variables, which is pointer variable. So the content in the arrays are the same in both (pointers).

anonymousstranger

  • New Member
  • *
  • Posts: 49
Re: array of objects or array of pointers?
« Reply #4 on: February 01, 2021, 12:40:13 pm »
Thank you. That really helps :)

 

TinyPortal © 2005-2018