2
votes

In Delphi, What is the difference between Constructor and Class function to instantiate an object?

TPersonnel = class(TPersistent)
public
  class function Create: TPersonnel; overload;
  constructor Create(APersonelID: integer); overload;
end;

class function TPersonnel.Create: TPersonnel;
begin
  result := inherited Create;
end;

constructor TPersonnel.Create(APersonelID: integer);
begin
  inherited Create;
end;

I Know that class function Create will hide default constructor.

Regardless constructor Create parameter

Is there a reason that I should use the constructor?

1

1 Answers

6
votes

Is there a reason that I should use the constructor?

Simply put, only a constructor can instantiate a new instance. A class function is not capable of creating a new instance.

For a class function to yield a new instance it must ultimately call a constructor in order to instantiate a new instance. And if you wish to write code that is executed when the instance is created, that should be placed in a constructor.

In your code's class function

class function TPersonnel.Create: TPersonnel;
begin
  Result := inherited Create;
end;

you are calling the inherited constructor with no parameters.