Constructors are class members that are used to initialize new class objects. Each call of a constructor creates a new object and returns a reference to it. A constructor can have parameters, a parameter set determines constructor signature. The use of the Inherited keyword in the constructor body results in the call of the specified basic class constructor on creating a derived class object. If the Inherited keyword is not specified, one can specify one of the constructors of the current class. To create objects, specify the New keyword before the constructor.
Take into account the following conditions when determining constructors:
If proper constructors are not determined in a class, the Create standard constructor is used.
If no constructor is determined in a derived class, parent class constructors will be inherited and used.
If a constructor (constructors) is determined in a derived class, only constructors of this class can be used to initialize objects. Parent class constructors will be unavailable.
Parent class constructors can be redetermined in a derived class.
It is allowed to call a constructor for already created object. In this case, only the constructor code will be executed without memory allocation and object fields initialization.
Class TestObject1: Object
_a: Integer;
Public Constructor Create(a: Integer = 0);
Begin
_a := a;
End Constructor Create;
Public Property A: Integer
Get
Begin
Return _a;
End Get
End Property A;
End Class TestObject1;
Class TestObject2: TestObject1
_b: Integer;
Public Constructor Create(b: Integer = 0);
Begin
Inherited Create(100);
_b := b;
End Constructor Create;
Public Property B: Integer
Get
Begin
Return _b;
End Get
End Property B;
End Class TestObject2;
Sub Main;
Var
Obj1: TestObject1;
Obj2: TestObject2;
Begin
Obj1 := New TestObject1.Create(100);
Obj2 := New TestObject2.Create(Obj1.A + 100);
Debug.WriteLine("A: " + Obj2.A.ToString);
Debug.WriteLine("B: " + Obj2.B.ToString);
End Sub Main;
The New operator is not required for classes that present the data types Boolean, Char, Currency, DateTime, Decimal, Double, Integer, TimeSpan, Variant, String. These types of variables are not references to objects but to objects themselves. Thus, the assignment operation looks as follows:
Sub Main;
Var
a: Integer;
Begin
a := 100;
End Sub Main;
See also: