Recent

Author Topic: Constructor question  (Read 1890 times)

Bart

  • Hero Member
  • *****
  • Posts: 5275
    • Bart en Mariska's Webstek
Constructor question
« on: January 09, 2016, 09:48:23 pm »
Hi,

Is this legal Pascal?

Code: [Select]
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:
Code: [Select]
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

marcov

  • Administrator
  • Hero Member
  • *
  • Posts: 11383
  • FPC developer.
Re: Constructor question
« Reply #1 on: January 09, 2016, 09:51:37 pm »
I think yes, memory allocation (tobject.newinstance) and constructor are separate.

If you are in the constructor, memory allocation (and zeroing) already has been done.

Bart

  • Hero Member
  • *****
  • Posts: 5275
    • Bart en Mariska's Webstek
Re: Constructor question
« Reply #2 on: January 10, 2016, 12:25:11 am »
Thanks.
It felt a bit unnatural doing this.

Anyhow, I think (for my real class) this cnstruct is a bit too odd for me.
I'll solve the problem I had in a different way.

Bart

 

TinyPortal © 2005-2018