Constructors are class members that implement the actions required to initialize a class or a new class instance. There are two types of constructors:
Instance. Instance constructors do not initialize a new class object. Each time such a constructor is called, a new object is created and a reference to it returns. A constructor can have parameters, which determine its signature. Instance constructors are not inherited by derived classes. The use of the Inherited keyword in constructor header results in invoking the specified basic class constructor when a derived class object is created. If the Inherited keyword is not present, it is possible to specify a constructor of the current class instead. If a class contains no instance constructor declarations, a default instance constructor is automatically provided. When creating objects, specify the New keyword before instance constructor.
Static. Static constructors initialize the class itself. Static constructors are not inherited by derived classes, cannot be called explicitly and cannot have parameters. A static constructor is executed only once for each an application domain on creating a class instance via instance constructor or on addressing any static class member.
Class A
//Overriden default constructor
Public Constructor Create();
Begin
End Constructor;
//Constructor with parameter
Public Constructor Create(i: integer);
Begin
End Constructor;
//Additional constructor with parameters
//On initialization, default constructor is called
Public Constructor CreateEx(i: integer; j: double): Create();
Begin
End Constructor;
End Class;
Class B: A
//Default constructor
//On initialization, constructor of the CreateEx basic class is called
Public Constructor B(): Inherited CreateEx(-1, -1);
Begin
End Constructor;
End Class;
Sub Test();
Var
Obj: A;
Obj1: B;
Begin
Obj := New A(); //Call the default constructor A.Create()
Obj := New A.Create(); //Explicitly call the default constructor A.Create()
Obj := New A(1); //Call constructor with the A.Create(i: Integer) parameter
Obj1 := New B(); //Call the default constructor B.Create()
End Sub;
Class UserObject
Public Shared i: Integer;
Public Shared s: String;
//This constructor will be called on the first addressing static fields
//or on creating an object instance
Shared Constructor Create();
Begin
i := integer.MinValue;
s := "Default";
End Constructor;
End Class;
See also: