Re: Only a fool or a politition answers his own questions. And I'm not a politition.


[ Delphi Forum ] [ Delphi Tutorials -- by DelphiLand ]

Posted by webmaster Guido on May 31, 2003 at 15:57:11:

In Reply to: Only a fool or a politition answers his own questions. And I'm not a politition. posted by Rhy on May 29, 2003 at 20:23:13:

When you declare a variable of type TInstruction, this does not create an object. So the next thing you have to do is explicitly *create* an object of the class TInstruction and put a *pointer* to that object in the variable. Lets look at an example:

var
  I1, I2: TInstruction; 
  begin
  I1 := TInstruction.Create; // create an object and let I1 point to it
  // Set some fields of I1, for example:
  I1.Text := 'ABC';
  I1.Number := 1;

What you probably did next, is something like this:

  I2 := I1; 

...and the result is, that I2 points to the SAME object as I1. Next I assume that you did the following:

  I2.Text := 'DEF'; 
  I2.Number := 2; 

...because I1 and I2 point to the same object, you have just changed the fields of that same object. It's exactly the same as if you did this:

  I1.Text := 'DEF'; 
  I1.Number := 2; 

What you should do instead is:

var
  I1, I2: TInstruction; 
begin
  I1 := TInstruction.Create; // create the first object, let I1 point to it
  I1.Text := 'ABC';
  I1.Number := 1;
  I2 := TInstruction.Create; // create the second object, let I2 point to it
  I2.Text := 'ABC';
  I2.Number := 1;

So, if you are working with an array of 24 elements, you have to create 24 different objects:

var
  InstSet: array[0..23] of TInstruction;
  I: integer;
begin
  // Create 24 objects and put pointers to them in the array:
  for I := 0 to 23 do
    InstSet[I] := TInstruction.Create;
  // Next, assign values to the fields of the objects:
  InstSet[0].Text := 'ABC';
  InstSet[1].Text := 'DEF';
  // and so on

In other words: it's not enough to declare a variable that will point to an object. In Delphi, objects are not created automatically. You have to explicitly create every object in your code.

What about the components that you put on forms at design time? These form-objects and component-objects are created "behind the scenes", through instructions that Delphi wrote for you in the project file (.DPR file).



[ Delphi Forum ]
[ DelphiLand: free Delphi source code, tips, tutorials ]