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:
inherited Create;
, initialize variables and so on.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?
Self
is not defined.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With