What is the difference between a constructor and a procedure in Delphi records?
Is there difference in behavior between a constructor call and a procedure call in Delphi records? I have a D2010 code sample I want to convert to D2009 (which I am using). The sample uses a parameterless constructor, which is not permitted in Delphi 2009. If I substitute a simple parameterless procedure call, is there any functional difference for records?
I.E.
TVector = record
private
FImpl: IVector;
public
constructor Create; // not allowed in D2009
end;
becomes
TVector = record
private
FImpl: IVector;
public
开发者_运维百科 procedure Create; // so change to procedure
end;
As far as I can see this should work, but I may be missing something.
The record constructors are absolutely unnessessary misleading syntax sugar in native Win32 code. The only difference between record constructor and procedure is syntax:
TVector = record
constructor Create;
end;
var
vec : TVector;
begin
vec:= TVector.Create;
and
TVector = record
procedure Create;
end;
var
vec : TVector;
begin
vec.Create;
AFAIK there is a difference in .NET code (I am not using .NET)
One point of minor interest is that a record constructor assumedly needs to be treated a little special internally versus a normal method since records by default have a default parameterless constructor which would have to be overridden with your custom version.
The other obvious difference between record constructors and record procedures is that your constructors must have at least one parameter defined. (Since records don't allow for inheritance and the default constructor has no parameters.)
A constructor is used to construct the record. It is called when the record is first created.
A function can and must be called as needed.
You can create a "constructing" procedure but you have to call it yourself.
TVector = record
private
FImpl: IVector;
public
procedure Create;
end;
var
vec : TVector;
begin
vec.Create;
An alternative is to create a factory function that returns the initialized record.
function CreateVector(): TVector;
begin
Result.Create;
end;
精彩评论