Constructor of the base class

Top  Previous  Next

What is translated > Types > Records, Classes, Interfaces > Class > Constructors > Constructor of the base class

 

In Delphi and C# the order of construction of the derived and the base classes is differently. In Delphi the derived class is constructed first, while in C# the constructors of the base classes are executed automatically, before the constructor of the derived class is executed. If the base class has no standard constructor (= constructor without parameters) the base class constructor has to be called in the initialization list with the according parameters.The constructors of the ancestor classes are executed in Delphi only, if they are called explicitly from in the written code. In such cases Delphi2C# tries to find this call and puts it into the initialization list:

 

 

type

TFoo = class

  constructor Create(Owner: TComponent);

end;

 

implementation

 

constructor TFoo.Create(Owner: TComponent);

begin                                                            

  inherited Create(Owner);                                                             

end; 

 

 

->

 

public class foo : TObject

{

  public foo(TComponent Owner)

  :  base(Owner)

  {

  }

 

}; 

 

 

There is a second reason, why this shift is necessary: in C# the explicit call of an ancestor constructor in the derived constructor has no effect. (A temporary instance of the base class will be created only.)

 

Base class constructors without parameters are called automatically in C#. Delphi2C# preserves the  original calls of such constructors as line comments.

 

constructor foo.Create();

begin                                                            

  inherited Create;                                                             

end; 

 

->

 

__fastcall foo::foo (  )

// inherited::Create;

}   

 

 

The example above was shortened. In fact Delphi2C# for each constructor creates a second function with the function body of the Delphi constructor.

 

 

type

TFoo = class

  constructor Create(Owner: TComponent);

end;

 

implementation

 

constructor TFoo.Create(Owner: TComponent);

begin                                                            

  inherited Create(Owner);                                                             

end; 

 

 

->

 

public class foo : TObject

{

  public foo(TComponent Owner)

  :  base(Owner)

  {

    Create(Owner);

  }

  public void Create(TComponent Owner)

  {

    //# base.Create(Owner);

  }

 

  public foo() {}

}; 

 

This additional method isn't a good programming style and even can produce errors, but it is needed, when a constructor is called directly to initialize an existing instance again.

 

 

var

foo : TFoo;

begin

foo := TFoo.Create;

foo := TFoo.Create(...):

 

 

 

 



This page belongs to the Delphi2C# Documentation

Delphi2C# home  Content