Search code examples
delphiclassconstructorreferencedelphi-2009

How can I create an Delphi object from a class reference and ensure constructor execution?


How can I create an instance of an object using a class reference, and ensure that the constructor is executed?

In this code example, the constructor of TMyClass will not be called:

type
   TMyClass = class(TObject)
     MyStrings: TStrings;
     constructor Create; virtual;
   end;

constructor TMyClass.Create;
begin
   MyStrings := TStringList.Create;
end;

procedure Test;
var
   Clazz: TClass;
   Instance: TObject;
begin
   Clazz := TMyClass;
   Instance := Clazz.Create;
end;

Solution

  • Use this:

    type
      TMyClass = class(TObject)
        MyStrings: TStrings;
        constructor Create; virtual;
      end;
      TMyClassClass = class of TMyClass; // <- add this definition
    
    constructor TMyClass.Create;
    begin
       MyStrings := TStringList.Create;
    end;
    
    procedure Test;
    var
      Clazz: TMyClassClass; // <- change TClass to TMyClassClass
      Instance: TObject;
    begin
       Clazz := TMyClass; // <- you can use TMyClass or any of its child classes. 
       Instance := Clazz.Create; // <- virtual constructor will be used
    end;
    

    Alternatively, you can use a type-casts to TMyClass (instead of "class of TMyClass").