Delphi Developer Certification Tips #2

Let's share the knowledge with your friends

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
    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;
The TMyClass could be instantiated using one of the following constructor:

  TMyClass.Create('Mike', 50);
  TMyClass.New('Mike', 50);
  TMyClass.Update('Mike', 30);

There are more to learn about Constructors and I suggest the following links:

Let's share the knowledge with your friends
4 replies
  1. Dennis
    Dennis says:

    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.

    • Andreano Lanusse
      Andreano Lanusse says:

      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.


Trackbacks & Pingbacks

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.