Schafsmann
Schafsmann

Reputation: 113

Delphi XE: class constructor doesn't get called in a class using generics

Consider the following example (I am using Delphi XE):

program Test;

{$APPTYPE CONSOLE}

type
  TTestClass<T> = class
  private
    class constructor CreateClass();
  public
    constructor Create();
  end;

class constructor TTestClass<T>.CreateClass();
begin
  // class constructor is not called. this line never gets executed!
  Writeln('class created');
end;

constructor TTestClass<T>.Create();
begin
  // this line, of course, is printed
  Writeln('instance created');
end;

var
  test: TTestClass<Integer>;

begin
  test := TTestClass<Integer>.Create();
  test.Free();
end.

The class constructur is never called and hence the line 'class created' is not printed. However, if I remove the generalisation and make TTestClass<T> into a standard class TTestClass, everything works as expected.

Am I missing something out with generics? Or it simply doesn't work?

Any thoughts on this would be apprechiated!

Thanks, --Stefan--

Upvotes: 11

Views: 2313

Answers (2)

David Heffernan
David Heffernan

Reputation: 612854

I can confirm that this is a bug. If the only instantiation of the class is in the .dpr file, then the class constructor does not run. If you create another unit, i.e. a separate .pas file, and instantiate a TTestClass<Integer> from there, then your class constructor will run.

I have submitted QC#103798.

Upvotes: 12

Henrick Hellstr&#246;m
Henrick Hellstr&#246;m

Reputation: 2666

Looks like a compiler bug. The same code works if you move the TTestClass declaration and implementation to a separate unit.

unit TestClass;

interface
type
  TTestClass<T> = class
  private
    class constructor CreateClass();
  public
    constructor Create();
  end;

var
  test: TTestClass<Integer>;

implementation

class constructor TTestClass<T>.CreateClass();
begin
  Writeln('class created');
end;

constructor TTestClass<T>.Create();
begin
  Writeln('instance created');
end;

end.

Upvotes: 9

Related Questions