[fpc-pascal] various ways of passing a class instance as a parameter

Martin Schreiber mse00000 at gmail.com
Tue Nov 15 10:58:05 CET 2011


On Tuesday 15 November 2011 10.33:13 Graeme Geldenhuys wrote:
> Hi,
> 
> What exactly is the difference (if any) between the parameter modifier
> when you pass a class instance to a procedure?
> 
> In the example below, I can define foo() as follows...
> 
> procedure foo(AClass: TStringList);
>   or

Take a copy of the AClass instance pointer.

> procedure foo(var AClass: TStringList);

Take the address of the instance variable. The instance pointer can be changed 
by the procedure, so the type of the instance variable must match TStringList 
exactly otherwise the procedure could store a wrong class into the instance 
variable. Example:

procedure foo(var AClass: TList);
begin
 aclass.free;
 aclass:= Tlist.create;
end;
[...]
var
 cl1: TStringList.
begin
 foo(cl1);       //does not compile
 //now there would be a TList in a TstringList variable

>   or
> procedure foo(const AClass: TStringList);
> 
Take a copy of the AClass instance pointer, AClass is readonly.

>   or
> procedure foo(constref AClass: TStringList);

Take the address of the instance variable, AClass is readonly.

Martin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20111115/57c82c4d/attachment.html>


More information about the fpc-pascal mailing list