0

When creating a class that inherits from another class, shouldn't it be true that when the derived class is created the base classes's constructor is called?

Type
  TBase = Class
    constructor xMain;
  End;
  TDerived  = Class(TBase)
    constructor xMain;
  End;

constructor TBase.xMain;
begin
  MessageBox(0,'TBase','TBase',0);
end;

constructor TDerived.xMain;
begin
  MessageBox(0,'TDerived','TDerived',0);
end;


Var
  xTClass:TDerived;
begin
  xTClass := TDerived.xMain;
end.

I thought this should result in a MessageBox displaying "TBase" and then "TDerived". Yet, this is not the case. When the above code is ran it only results in one MessageBox displaying "TDerived".

Josh Line
  • 625
  • 3
  • 13
  • 27

2 Answers2

9
constructor TDerived.xMain;
begin
  inherited;
  MessageBox(0,'TDerived','TDerived',0);
end;
bummi
  • 27,123
  • 14
  • 62
  • 101
6

add inherited in TDerived.xMain; otherwise the code from ancestor will not be called;

begin
  inherited;//call the ancestor TBase.xMain
  MessageBox(0,'TDerived','TDerived',0);
end;

Also this question will help you understand inherited reserved word:

Delphi: How to call inherited inherited ancestor on a virtual method?

another good resource is http://www.delphibasics.co.uk/RTL.asp?Name=Inherited

Community
  • 1
  • 1
RBA
  • 12,337
  • 16
  • 79
  • 126
  • You also may want/need to call inherited for overridden methods - IF you want to perform the ancestor methods functionality and then add to it. – Toby Dec 30 '16 at 17:40