[fpc-pascal] parent class as a parameter type

Mattias Gaertner nc-gaertnma at netcologne.de
Thu Nov 17 19:07:17 CET 2011


On Thu, 17 Nov 2011 15:15:46 +0100
Sven Barth <pascaldragon at googlemail.com> wrote:

> Am 17.11.2011 15:07, schrieb ik:
> > On Thu, Nov 17, 2011 at 16:03, Sven Barth <pascaldragon at googlemail.com
> > <mailto:pascaldragon at googlemail.com>> wrote:
> >
> >     Am 17.11.2011 09:23, schrieb ik:
> >
> >             It's not allowed in Delphi in case of a var/out parameter. It's
> >             allowed in both FPC and Delphi in case of a value/const
> >         parameter.
> >
> >
> >         Sorry for the late response, but why does out and var limit this
> >         issue ?
> >         I understand that it does, but not the reason for it.
> >
> >
> >     The reason is mentioned in the link I sent you:
> >     http://wiki.freepascal.org/__User_Changes_2.6.0#Passing___derived_classes_to_var-_and___out-parameters
> >     <http://wiki.freepascal.org/User_Changes_2.6.0#Passing_derived_classes_to_var-_and_out-parameters>
> >
> >
> > I read it, but I do not understand it.
> >
> > TStrings is a class. TStringList is a class inherited from TStrings. How
> > does it prevent the type checking ?
> > As I remember, if I placed there "TFom" based class, it will not like it
> > and report and error. That's why I do not understand it I guess.
> 
> Emagine the following code:
> 
> procedure Foo(var aList: TStrings);
> begin
>    aList.Free;
>    aList := TStrings.Create;
> end;
> 
> var
>    l: TStringList;
> begin
>    l := TStringList.Create;
>    Foo(l);
>    l.Sort;
> end.
> 
> When you run this code you will have a big problem. Your "l" variable is 
> a TStringList, but after calling Foo your variable holds a TStrings 
> instance (which is lower in the hierarchy than TStringList)! If you now 
> call Sort you will get an access violation if you're lucky or some 
> strange error if not, because Sort is introduced by TStringList. Thus 
> you call into "nothing" when executing this on a TStrings.
> 
> Is the reason why this is forbidden more clear now?

The l.Sort is the important line, that is missing in the wiki example.

Maybe this example can replace the example in the wiki?

Mattias



More information about the fpc-pascal mailing list