Name
Constructor Keyword
Syntax
typeClass declaration... constructorName; constructorName(Arguments...); end;
Description
A constructor is a special kind of method. If you call a constructor using a class reference, Delphi creates a new instance of that class, initializes the instance, and then calls the constructor proper. If you call a constructor using an object reference, Delphi calls the constructor as an ordinary method.
A natural consequence of Delphi’s rules is that a constructor
can call another constructor of the same class or call an inherited
constructor. The call uses an object reference (namely,
Self) so the constructor is called as an ordinary
method.
When called using a class reference, Delphi calls the
NewInstance method to create the instance.
TObject.NewInstance allocates memory for the new
object and fills that memory with all zeros, but you can override
NewInstance to create the object in a different
manner.
Tips and Tricks
A common error for new Delphi programmers is to call a constructor using an object-type variable. Rather than creating the object, such a call invariably results in access violations because the object reference is most likely invalid. The compiler can warn you about such errors if you enable compiler warnings in the project options. For example:
var ObjRef: TSomething; begin ObjRef.Create; // wrong ObjRef := TSomething.Create; // right
If you are writing an abstract base class, and the constructor is virtual so you can write a class factory, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access