[fpc-pascal] Constructor question

Mattias Gaertner nc-gaertnma at netcologne.de
Sat Jan 9 23:44:55 CET 2016


On Sat, 9 Jan 2016 21:46:19 +0100
Bart <bartjunk64 at gmail.com> wrote:

> Hi,
> 
> Is this legal Pascal?
> 
> uses
>   classes,sysutils;
> 
> type
>   { TA }
>   TA = class
>     protected
>     F1: Integer;
>     F2: Integer;
>     public
>     constructor Create; virtual;
>   end;
>   { TB }
>   TB = Class(TA)
>     constructor Create; override;
>   end;
> 
> { TB }
> constructor TB.Create;
> begin
>   writeln('TB.Create');
>   F1 := 1;                // am I allowed to access F1 before calling
> inherited Create?

Yes.

>   F2 := 2;
>   inherited Create;
> end;
> { TA }
> constructor TA.Create;
> begin
>   writeln('TA.Create: F1 = ',F1,' F2 = ',F2);
> end;
> 
> 
> var
>   A,B: TA;
> begin
>   A := nil;
>   B := nil;
>   try
>     try
>       A := TA.Create;
>       B := TB.Create;
>     except
>       on E: Exception do writeln(E.ClassName,': ',E.Message)
>     end;
>   finally
>     if Assigned(A) then A.Free;
>     if Assigned(B) then B.Free;
>   end;
> end.
> 
> 
> Q: am I allowed to access a property/field of TA in the constructor of
> TB before calling inherited Create there?

Yes.

 
> It compiles and it ouputs:
> TA.Create: F1 = 0 F2 = 0
> TB.Create
> TA.Create: F1 = 1 F2 = 2
> 
> This is what I intended, but is it legal, or does it just work by chance?

It works by design.

Mattias



More information about the fpc-pascal mailing list