[fpc-devel] Warning: Constructor should be public

Graeme Geldenhuys graemeg.lists at gmail.com
Tue Apr 7 00:11:07 CEST 2009


On Mon, Apr 6, 2009 at 10:37 PM, Léo Willian Kölln <leokolln at gmail.com> wrote:
> No.
> See my singleton example:

How did I guess it was going to be about implementing a Singleton.
This issue has been raised a thousand times in FPC and Delphi circles.
:)

>
> TLoggerGeral = class

Which means you are descending from TObject.

>  private
>  {$IFDEF WINDOWS}
>    class var FInstance : TLoggerGeral;
>  {$ELSE}
>    {$STATIC on}
>    FInstance : TLoggerGeral; static;
>  {$ENDIF}
>
>    constructor Create;

Which means you are trying to lower the constructor TObject.Create
from public to private.

>
> A normal singleton and it complain!

I have a much easier "lazy man's" singleton for you... It's not 100%,
but then, I have *never* seen a singleton implementation in Delphi or
FPC that is 100%.  Simply access the singleton via the gMySingleton
method.

eg:
   gMySingleton.DoSomethingCool;

========================
interface

   TMySingleton = class(TObject)
   ...
   end;

function gMySingleton: TMySingleton

implementation

var
  uMySingleton: TMySingleton;

function gMySingleton: TMySingleton;
begin
  if not Assigned(uMySingleton) then
    uMySingleton := TMySingleton.Create;
  result := uMySingleton;
end;

[...snip the rest of TMySingleton implementation...]

initialization
  uMySingleton := nil;
finalization
  uMySingleton.Free;

end.
========================


The reason you can't lower the visibility of the constructor or any
method for that matter... A class interface (implementation section) ,
even for TObject as in your example, is a contract of how you can use
that class and what is available to you.  By lowering the visibility
of a method or constructor in a descendant class, you are breaking the
contract previously defined. This is a BIG no-no, hence the reason it
is not allowed.


Regards,
  - Graeme -


_______________________________________________
fpGUI - a cross-platform Free Pascal GUI toolkit
http://opensoft.homeip.net/fpgui/



More information about the fpc-devel mailing list