[fpc-pascal] Implementing a true Singleton - Can we decrease the visibility of a method?

Vincent Snijders vsnijders at quicknet.nl
Fri Dec 8 09:57:54 CET 2006


Graeme Geldenhuys schreef:
> Bottom line: How can we hide the constructor of a class?  As far as I
> can see you cannot decrease the visibility of a method compared to
> it's inherited class. Why shouldn't we be allowed to?  C++, C# does!
> 
> I found this by trying to implement a True Singleton in Free Pascal /
> Delphi.  For those that don't know, a Singleton is a Design Pattern
> that allows only one instance of a class.  It seems it is impossible
> to do in Free Pascal / Delphi.  :-(
> 
> See attached code for a demonstration of the problem.
> 
> And here is the output.  The first two '>> PrintData' sections are
> correct and use the singleton as it should be used.  The third '>>
> PrintData' section is by declaring a new variable of TSingleton and
> creating it.
> 
> The problem is even though the constructor is declared in the
> protected section, Free Pascal just gives a compiler warning and it
> stays public.  What is the reason why we may not decrease visibility
> of methods or properties?  Couldn't we add this feature to Free
> Pascal? Or at least in the ObjFPC mode!

Maybe I am analyzing your output wrong, but to me it seems as if the contructor of 
TObject is called in the third case. printdata seems to print an empty text.

So the protected contructor is unreachable, but the public constructor in TObject 
remains public.

Vincent



More information about the fpc-pascal mailing list