Delphi Developer Certification Tips #2
Here I am with the second tip for the Delphi Developer Certification and it’s about constructor.
Every Delphi Developer should know that every single class has a Constructor method, which is used to create the object. The RAD Studio documentation describe the Constructor as:
A constructor is a special method that creates and initializes instance objects. The declaration of a constructor looks like a procedure declaration, but it begins with the word constructor.
It is conventional to call the constructor Create, a class can have more than one constructor, but most of the time we just see one. Since what define the class constructor is the keyword constructor, you can call it whatever you want. There are many situations where you will need multiple constructors, in general we don’t use multiples names, but the capability to give different names for the constructor could help to have a better understating of the code. The following example has 7 different constructors using three different names Create, New and Update:
TMyClass = class public name : string; constructor Create; overload; // This constructor uses defaults constructor Create(name : string); overload; constructor Create(name : string; age : Integer); overload; constructor New(name : string);overload; constructor New(name : string; age : Integer);overload; constructor Update(name : string);overload; constructor Update(name : string; age : Integer);overload;
end;
The TMyClass could be instantiated using one of the following constructor: TMyClass.Create; TMyClass.Create('Mike'); TMyClass.Create('Mike', 50); TMyClass.New('Mike'); TMyClass.New('Mike', 50); TMyClass.Update('Mike'); TMyClass.Update('Mike', 30);
There are more to learn about Constructors and I suggest the following links:
Why would one need multiple named constructors? I don’t think this could help to have a better understanding of the code – it makes it even worse.
Hi Dennis,
We already fixed the problem with the certification kit.
Related with different name for constructors. I disagree, sometimes the Create name is not the most appropriated to represent the class construction, for example if you have a ORM framework, there are situations where you need to instantiate the class for update, delete or create a record, and different name in this case would be better IMO.