Dynamic instantiation of classes

I have a certain class defined. Let's say:
class someClass
   constructor create(const a: integer);
   ...
end;

During runtime I need to create instances of that class, yet I cannot know until rutime how many objects will be required (of course, for each instance of the class, the constructor should be called).

What would be the best way to create instances of this class in runtime and manage a list of all the object I have created from that class so I can access their methods etc.?

Note that instances of this class shoukd be created from within a function yet remain viable after the function exits because other functions should use those objects.
mathoughtAsked:
Who is Participating?
 
ITugayCommented:
uses cntnrs;

var CList : TObjectList;


procedure SomeCreate;
var I : integer;
begin
   for I:=1 to 50 do CList.Add(TYourClass.Create(I));
end;


procedure DoSomething;
begin
   TYourClass(CList[5]).YourMethod;
end;
----
Igor.

Do not forget to initialize CList;


0
 
mathoughtAuthor Commented:
I use Delphi 4 and:
Does not recognize "TObjectList" nor "uses cntnrs"

anyway, I used TList instead of TObjectList and it worked. (Am I missing anything?)
0
 
EpsylonCommented:
That should be contnrs


Or use TList instead:

CList.Add(Pointer(TYourClass.Create));


The rest is like Igor says.

Regards,

Epsylon.
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
mathoughtAuthor Commented:
Helped me, but was a little bit inaccurate.
0
 
EpsylonCommented:
>but was a little bit inaccurate

How about 'Thanks' or something like that? We answer questions in our own time you know...
0
 
mathoughtAuthor Commented:
You are right, sorry.
I truely thank you both.

But The points did belong to Igor.
0
 
EpsylonCommented:
>The points did belong to Igor

No problem, I agree  :o)

Cheers,

Epsylon.
0
 
ITugayCommented:
The main difference of TList and TObjectList:

----- TObjectList Delphi help --------
If the OwnsObjects property is set to True (the default), TObjectList controls the memory of its objects, freeing an object when its index is reassigned; when it is removed from the list with the Delete, Remove, or Clear method; or when the TObjectList instance is itself destroyed.
----- end------

TList did't free items automatically.

-----
Igor.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.