Josh Line
Josh Line

Reputation: 635

Delphi XE2 - Inheriting class not calling base class' constructor...?

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".

Upvotes: 0

Views: 507

Answers (2)

RBA
RBA

Reputation: 12584

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

Upvotes: 6

bummi
bummi

Reputation: 27367

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

Upvotes: 9

Related Questions