qwertyuiopasdfghjkl
asked on
Pass by Reference ?
every time i use 'var' (pass by Reference) for my procedure or function the following code give me a error message [Error] (45): Types of actual and formal var parameters must be identical, why ?
Caller
-------
var
Button1 : TButton;
Panel1 : TPanel;
Begin
SetParent(Button1,Panel1);
End;
Procedure
----------
procedure SetParent(var AChild , AParent : TWincontrol);
Begin
AChild.Parent := AParent;
end;
Caller
-------
var
Button1 : TButton;
Panel1 : TPanel;
Begin
SetParent(Button1,Panel1);
End;
Procedure
----------
procedure SetParent(var AChild , AParent : TWincontrol);
Begin
AChild.Parent := AParent;
end;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
By the way, I think you shold change the name for the procedure, since setparent is a Win32API's name, so sometimes you can get confused.
Wang's suggestions were exactly right :)
Yes dwwang is right but has missed the point I think!
Neither parameter needs to be var. When passing objects as var parameters you are saying that the reference to the object cannot be chaged, however all members of an object passed by value may be changed.
The SetParent function (ignoring the naming issue) would best be written as:
procedure SetParent(const AChild, AParent : TWincontrol);
Begin
AChild.Parent := AParent;
end;
This also avoids the need for the ghastly unsafe typecasts.
Cheers,
Raymond.
Neither parameter needs to be var. When passing objects as var parameters you are saying that the reference to the object cannot be chaged, however all members of an object passed by value may be changed.
The SetParent function (ignoring the naming issue) would best be written as:
procedure SetParent(const AChild, AParent : TWincontrol);
Begin
AChild.Parent := AParent;
end;
This also avoids the need for the ghastly unsafe typecasts.
Cheers,
Raymond.
Yes, agree with Raymond, actually changing properties of object need not pass as reference.
Since objects are already pointers in Delphi, reference calling is only needed in stuations that you need to "change themselves", e.g.:
procedure CreateControl(var ret,aParent:TWincontrol);
begin
ret:=TEdit.Create(aParent) ;
end;
Anyway, I was just answering his original question, sorry for not giving further discussion :-)
Regards,
Wang
Since objects are already pointers in Delphi, reference calling is only needed in stuations that you need to "change themselves", e.g.:
procedure CreateControl(var ret,aParent:TWincontrol);
begin
ret:=TEdit.Create(aParent)
end;
Anyway, I was just answering his original question, sorry for not giving further discussion :-)
Regards,
Wang