Forum > Beginners

Is there an easy way to initialize an array of objects in free pascal? [SOLVED]

<< < (2/2)

avk:
FPC-3.3.1 supports constructors for static arrays. So it seems possible to write

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---  persons := [TPerson.Create('John', 1.77, 90), TPerson.Create('Maria', 1.65, 52), TPerson.Create('Jim', 1.85, 95)]; 
or even

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---...function Person(p_name: string; p_height: real; p_weight: integer): TPerson;begin  Result := TPerson.Create(p_name, p_height, p_weight);end;...  persons := [Person("John", 1.77, 90), Person("Maria", 1.65, 52), Person("Jim", 1.85, 95)];  

dje:
I could be wrong (I'm not a C++ expert), but since the C++ code isn't using the new operator, then the Pascal equivalent is object types or advanced records. Using a class in this situation will create a minefield of memory leaks, and you may then blame Pascal.

I would implement as such:


--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---type   TPerson = object    Name: String;    Num1, Num2: Single;  end; function Person(Name: String; Num1, Num2: Single): TPerson;begin  Result.Name := Name;  Result.Num1 := Num1;  Result.Num2 := Num2;end; var Persons: array of TPerson; begin  Persons := [Person('John', 1.77, 80), Person('Maria', 1.65, 52), Person('Jim', 1.85, 95)];  end. 
If you really need OOP then you should be using a storage method which owns the objects. ie: TComponent, TObectList, etc.

YiannisKam:
Sorry for my delayed reply guys. Thank you all for the information. I've downloaded the FPC-3.3.1 trunk version.

Navigation

[0] Message Index

[*] Previous page

Go to full version