ReRe: Delphi procedure declaration var

Posted by John, DelphiLand Team

In Reply to Re: Delphi procedure declaration var posted by Pinguin

: Isn't it possible to force Delphi to really pass an object by value?
: I have to write something like the following:
: [ ...code... ]
: This will only work if I can force Delphi to make a copy of A. Otherwise, when I clear C, it will also clear A :(
: The only solution I got is to make the copies myself.

A Delphi object can only be passed by reference, because it doesn't have a value. An object only has fields, properties and methods (procedures and functions).

Solutions:

1. As you mentioned already, make a local copy of the value that you are clearing but that you need later on:

procedure DS(A, B, C: aClass);
var
  xTemp: integer;
begin
  xTemp := A.GetX; // remember A.x 
  C.SetX(0);       // A.x is reset to 0
  ....
  C.SetX(xTemp + B.GetX);
end;
 
procedure aClass.SomeProcedure;
var
  A, B: aClass;
begin
  A.Create();
  B.Create();
  A.x := 5;
  B.x := 1;
  DS(A, B, A);
  ...
end;

2. Or you could pass A.x "by value":

procedure DS(x: integer; B, C: aClass);
begin
  C.SetX(0); 
  ....
  C.SetX(x + B.GetX);
end;
 
procedure aClass.SomeProcedure;
var
  A, B: aClass;
begin
  A.Create();
  B.Create();
  A.x := 5;
  B.x := 1;
  DS(A.x, B, A);
  ....
end;

A short clarification: you wrote "when I clear C". What you are doing, is in fact change a FIELD of C,
whereas "clearing" C would be: C := nil

John, DelphiLand Team

Related articles

       

Follow Ups