In Delphi, if I have a simple class myClass
and I pass an instance of it to a function with myFunction( myClass )
, which is defined by function myFunction( myObject : myClass ) : Boolean
...
Will a copy of myObject be made?
When I call methods of myObject in myFunction, will the original object be affected and modified too?
Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument. When the called function read or write the formal parameter, it is actually read or write the argument itself.
In Delphi to pass by reference you explicitly add the var keyword: procedure myFunc(var mytext:String); This means that myFunc can modify the contents of the string and have the caller see the changes.
In case you don't want to use 'var' for any reason, you can pass an address of the data to your method. But as you can't use syntax 'data: ^array of integer' in parameter declaration, you'd have to declare a type for your data. And you'd have to use 'data^' instead of 'data' everywhere in the method.
“Passing by value” refers to passing a copy of the value. “Passing by reference” refers to passing the real reference of the variable in memory.
Objects are passed by reference. A copy will not be made; there will be only one instance of the class, only one object. The original object is all there is.
In Delphi, objects are special pointers which refer to a data structure on heap memory. When you pass an object to a function, you are actually passing the pointer, not a copy of the whole object data. In this case, when you modify a field or property via that reference, it will affect the original object data. Here is a simple example demonstrating this behavior:
program ObjParamTest;
type
TMyClass = class
private
FMyField : Integer;
public
property MyField : Integer read FMyField write FMyField;
end;
function ModifyObject(AnObj: TMyClass);
begin
AnObj.MyField := AnObj.MyField + 1;
end;
var
MyObj : TMyClass;
begin
MyObj := TMyClass.Create;
try
AnObj.MyField := 2;
Writeln(AnObj.MyField); // ==> Prints 2
ModifyObject(MyObj);
Writeln(AnObj.MyField); // ==> Prints 3
finally
MyObj.Free;
end;
end.
Also take note, parameter modifiers (e.g. Var, Const, Out) only change the way the object reference is passed to the function, and have no effect on the original data structure.
Maybe this article clears up things about different ways of passing parameters to functions in Delphi for you more:
Different function parameter modifiers in Delphi (archived version)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With