Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to instantiate a desired number of objects in Delphi, without iterating?

I think that C++ supports something on the lines of :

Object objects[100];

This would instantiate a 100 objects, right? Is it possible to do this in Delphi (specifically 2007)? Something other than:

for i:=0 to 99 do
  currentObject = TObject.Create;

or using the Allocate function, with a passed size value a hundred times the TObject size, because that just allocates memory, it doesn't actually divide the memory and 'give' it to the objects. If my assumption that the c++ instantiation is instant rather than under-the-hood-iterative, I apologize.

like image 369
programstinator Avatar asked Dec 09 '22 20:12

programstinator


2 Answers

What you are looking for is impossible because

  • Delphi does not support static (stack allocated) objects.
  • Delphi objects do not have default constructors that can be automatically invoked by compiler.

So that is not a lack of 'sugar syntax'.


For the sake of complete disclosure:

  • Delphi also supports legacy 'old object model' (Turbo Pascal object model) which allows statically allocated objects;
  • Dynamic object allocation itself does not prevent automatic object instantiation syntax, but makes such a syntax undesirable;
  • Automatic object instantiation syntax is impossible because Delphi does not have default constructors: Delphi compiler never instantiate objects implicitly because it does not know what constructor to call.
like image 159
kludg Avatar answered Feb 22 '23 22:02

kludg


While you can't do what you want using objects, if your objects are relatively simple, you may be able to get what you want by using an array of records.

Records in Delphi can have properties (including setters and getters), and class and instance methods. They are created automatically when declared, so declaring an array of them will create them all without iterating.

For more info: http://docwiki.embarcadero.com/RADStudio/XE3/en/Structured_Types#Records_.28advanced.29.

(I'm not sure when the new functionality was added to Delphi, it may well be after the 2007 version).

like image 41
Larry Lustig Avatar answered Feb 22 '23 22:02

Larry Lustig