Re: Create() problems in Delphi

Posted by William

In Reply to: Create()-probs posted by Martin Knappe

: ... : create objects of my own TEntry class and then insert them into a list of my own-defined list class (which inherits from TList; referenced by self here) but it seems like every time I invoke Create I get the same pointer back, so in the end I'm creating only one object!!! Have a look at this one:

var
  ...
  P: Pointer;
  Entry: TEntry;
begin
  P := nil;
  ...
  while ...
    Entry := TEntry.Create();
    if P = Addr(Entry) then
      ShowMessage('Same address!!!');
    ...
    Self.Add(Addr(Entry));
    P := Addr(entry);
  end;
  ...
end; 

: [...] always get the 'Same address!!!' message. This is not what I intend. I obviously intend to create [...] objects and have them all added to my list.
-------------------------

You are not comparing the POINTERS that you receive from Create(), but you are comparing ADDR(Entry) and of course that is always the same.

Here is the correct way:

var
  ...
  Entry, PreviousEntry: TEntry;
begin
  PreviousEntry := nil;
  while ...
    Entry := TEntry.Create();
    if Entry = PreviousEntry then
      ShowMessage('Same object!);
    Self.Add(Entry);
    PreviousEntry := Entry;
    ...
  end;
  ...
end;

DelphiLand Discussion Forum