Inheritance in Delphi : Does each of Delphi Subclasses have its own unique copy of the Superclass Private Fields?

Viewed 154

Suppose we have a Delphi SuperClass (TSuper) and we inherit a group of Subclasses from it ( TSub1 , TSub2 ). This Superclass (TSuper) has only one Private Field ( FField ).

The Subclasses ( TSub1, TSub2 ) do not have their concrete real Fields at all as shown in the code below (this is for testing!), instead they inherit the Private field of their ancestor.

unit Unit1;

interface

uses
  Winapi.Windows,
  Winapi.Messages,
  System.SysUtils,
  System.Variants,
  System.Classes,
  Vcl.Graphics,
  Vcl.Controls,
  Vcl.Forms,
  Vcl.Dialogs;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

Type
  TSuper = class
  private
    FField: integer;
  public
    constructor Create;
    Property Int: integer read FField write FField;
  end;

  TSubOne = class(TSuper)
  public
    constructor Create;
  end;

  TSubTwo = class(TSuper)
  public
    constructor Create;
  end;

var
  Form1: TForm1;
  vSuper: TSuper;
  vOne: TSubOne;
  vTwo: TSubTwo;

implementation

{$R *.dfm}
{ TSuper }

constructor TSuper.Create;
begin
  self.FField := 0;
end;

{ TSub }

constructor TSubOne.Create;
begin
  self.FField := 1;
end;

{ TSubTwo }

constructor TSubTwo.Create;
begin
  self.FField := 2;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  vSuper := TSuper.Create;
  vOne := TSubOne.Create;
  vTwo := TSubTwo.Create;

  ShowMessage('Field of Super Class = ' + inttostr(vSuper.Int));
  ShowMessage('Field of Sub Class One = ' + inttostr(vOne.Int));
  ShowMessage('Field of Sub Class Two = ' + inttostr(vTwo.Int));
end;

end.

When we run the code above, we notice that if we assign different values for each of the 3 classes Field (TSuper, TSub1, and TSub2 ), they will return the correct value for each.

From this, it seems that Delphi will create a hidden , unique ( different ) copies of the Superclass's private field within each of its Subclasses.

Is this correct? can we really depend on this feature? or it is only a temporary feature in an ideal situation that will work differently under any circumstances!

where can I found the explanation of this behavior in the Documentation?

Thank you.

1 Answers

Does each of Delphi Subclasses have its own unique copy of the Superclass Private Fields?

Yes, each object instance of a subclass has his own set of all fields defined in the entire class hierarchy.

If you need data that is common for all instance of a class, you need to define it as a class property using the keyword class.

For more details, have a look at Delphi documentation.

Related