Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2016-01

Constructor question

3 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Bart

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?
  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?

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?

Bart

Mattias Gaertner
to Bart
Show quoted text 27 lines
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.

Show quoted text 31 lines
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.

Show quoted text 6 lines
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

Bart
to Mattias Gaertner
Mattias Gaertner wrote 6 lines
> Q: am I allowed to access a property/field of TA in the constructor of > TB before calling inherited Create there? > This is what I intended, but is it legal, or does it just work by chance? It works by design.

Thanks for clarifying.

Bart