Вопрос

Guys to my surprise i see that a "double call" to the constructor of an object is acceptable by the compiler. Any idea what purpose does this serve and what would be the result of such a function?

procedure TForm1.Button1Click(Sender: TObject);
var
  vLabel : Tlabel;
begin
  vLabel := Tlabel.Create(self).Create(self);
end;
Это было полезно?

Решение

The second call to Create works like a regular procedure call: it omits any of the special construction code and only performs the user code in the constructor. In practice this is very useful to be able to call other constructors from the implementation of a constructor:

constructor TLabel.CreateHello(AOwner: TComponent);
begin
  // Perform default construction.
  Create(AOwner);
  // Set default text.
  Caption := 'Hello';
end;

Compare this to C++ where you have to move shared logic for multiple constructors to a separate function because you can't call a constructor once the object has been created. The Delphi solution is elegant and encourages code reuse.

To implement this, there is a hidden extra boolean parameter for constructors that specifies whether to perform full construction logic (e.g. memory allocation) or not.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top