Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi constructor and class constructor

Tags:

delphi

I have a doubt that I cannot solve. I have read the documentation at embarcadero for class constructors but I cannot understand the meaning of that. In other words, what is the usage difference between a constructor and a class constructor? I did this:

type
 TGeneric<T> = class
  private
   FValue: T;
   aboutString: string;
   procedure setValue(const a: T);
  public
   property V: T read FValue write setValue;
   property about: string read aboutString;
   constructor Create;
   destructor Destroy; override;
 end;

implementation

{ TGeneric<T> }

constructor TGeneric<T>.Create;
begin
  inherited;
  aboutString := 'test';
end;

Instead this code is not working properly:

type
 TGeneric<T> = class
  private
   FValue: T;
   aboutString: string;
   procedure setValue(const a: T);
  public
   property V: T read FValue write setValue;
   property about: string read aboutString;
   class constructor Create;
   destructor Destroy; override;
 end;

implementation

{ TGeneric<T> }

class constructor TGeneric<T>.Create;
begin
  inherited;
  aboutString := 'test';
end;

I guess that the answer is in this line of the documentation:

Normally, class constructors are used to initialize the static fields of the class or to perform a type of initialization, which is required before the class or any class instance can function properly.

Tell me if I am correct:

  • Constructor: I can use the inherited Create;, initialize variables and so on.
  • Class constructor: I can use this when I have to create an object in my class immediately?

For example look at below:

type
   TBox = class
   private
     class var FList: TList<Integer>;
     class constructor Create;
   end;

 implementation

 class constructor TBox.Create;
 begin
   { Initialize the static FList member }
   FList := TList<Integer>.Create();
 end;

 end.

Here I am going to create the object immediately when I call TBox.Create in the main form?

like image 919
Raffaele Rossi Avatar asked Sep 13 '16 13:09

Raffaele Rossi


Video Answer


1 Answers

  • A class constructor executes exactly once, when the unit in which it is declared is initialized. A class constructor is a static class method, and so Self is not defined.
  • A constructor executes when explicitly called and has the job of initializing an instance of a class.

In the wild, class constructors are rare, constructors are as common as muck. Quite likely you have no immediate need for class constructors so feel free to ignore them for now. Concentrate on understanding how to write and use constructors.

If in the future you ever need to initialize variables owned by the class (as opposed to owned by an instance) then you might find yourself wanting to use a class constructor. Until that point in time, do feel free to ignore them.

like image 110
David Heffernan Avatar answered Sep 22 '22 07:09

David Heffernan