[fpc-pascal] Class constructor called unconditionally

silvioprog silvioprog at gmail.com
Thu Mar 31 15:32:27 CEST 2016


Hello,

First, take a look at this small project:

=== code ===

program Project1;

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$IFDEF MSWINDOWS}
  {$APPTYPE CONSOLE}
{$ENDIF}

type
  TFoo = class
  public
    class constructor Create;
  end;

  class constructor TFoo.Create;
  begin
    Writeln('TFoo.Create called');
  end;

begin
  Writeln('Program start');
  Readln;
end.

=== /code ===

When you compile and run it in FPC, the result is:

=== result ===

TFoo.Create called
Program start

=== /result ===

But, if you compile and run this same code in Delphi (I'm using Seattle),
the result is:

=== result ===

Program start

=== /result ===

Googling about this problem, I found this link at StackOverflow:

http://stackoverflow.com/questions/6231871/class-constructor-not-called-when-class-registration-is-done-in-that-class-const

With this comment:

"Uwe Raabe answered Jun 3 '11 at 19:55: As long as you don't use the class
anywhere outside the class itself, the compiler takes this as the class not
used at all and hence won't call the class constructor. So I guess you have
to use the intialization section instead of tweaking the code to fool the
compiler. Take the pragmatic approach instead of the dogmatic one. It will
be more readable anyway."

After read this explanations, is there some compiler option to make FPC
with this same Delphi behaviour? I'm using MODE DELPHI.

Thank you!

-- 
Silvio Clécio
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20160331/86500754/attachment.html>


More information about the fpc-pascal mailing list