Constructor delegation

Top  Previous  Next

What is translated > Types > Records, Classes, Interfaces > Class > Constructors > Constructor delegation

 

A constructor can call another constructor in it's body:

 

type

  TFoo = class(TBase)

 

    constructor Create(s : string); overload;

    constructor Create(b : PChar; l : integer); overload;

...

 

implementation

 

 

constructor TFoo.Create(s : string);

begin

  inherited Create;

  Create(PChar(s), length(s))

end;

 

 

A direct translation of the constructor definition would look like:

 

TFoo::TFoo(String s)

{

  TFoo(ustr2pwchar(s), s.size()),

}  

 

However, this does not the same as in Delphi. In C++ the call of the second constructor in the body of the first only creates a temporary local second TFoo object, which has no effect to the current instance. But in C++11 there is the new feature to call the second constructor instead of an initialization list 

 

 

TFoo::TFoo(String s)

 : TFoo(ustr2pwchar(s), s.size())  //# delegation

{

 

}

 

Though this construction doesn't work for C++98 compiler, Delphi2Cpp nevertheless translates the code in this way too, because there is no gneral alternative solution. For C++98 the code has to be post-processed manually.

 

 

 

 

 

 



This page belongs to the DelphiXE2Cpp11 Documentation

DelphiXE2Cpp11 home  Content