[fpc-pascal] WHY compiler should be public?
Xiangrong Fang
xrfang at gmail.com
Fri Oct 25 06:22:05 CEST 2013
Hi,
First of all, I did some research and found this:
http://free-pascal-general.1045716.n5.nabble.com/Compiler-Warning-Constructor-should-be-public-td2825747.html
But that did not convince me. So here is my situation and question.
I have the following case:
TBase = class
public
constructor Create; //VER-0
end;
TDerived = class(TBase)
private
constructor Create(param1); //VER-1
public
constructor Create; reintroduce; //VER-0'
constructor Create(param1, param2); //VER-2
constructor Create(param1, param2, param3); //VER-3
end;
My purpose is that while using TDerived, only VER-2
and VER-3 of the constructors should be used, VER-0
and VER-1 are used INTERNALLY by VER-2 and VER-3 and
should NOT be used publicly.
As restricted by the "rule of OOP", you cannot make a
method which is public in base class private in descendants,
I plan to do the following:
1) reintroduce a Create (without param), which just throw
an exception explaining that this MUST NOT be called directly.
Meanwhile, use "inherited Create" internally in other versions
of the constructors.
2) Make VER-1 private so that it cannot be called outside.
Now the compiler throw a warning that constructor should be
public.
In the post I referred, Graeme explained that:
==============================================================
Your code is flawed. Object Pascal is quite clear regarding
visibility rules. TObject has a Public constructor. You can
only raise the visibility from there, not reduce visibility.
Imagine how confusing it will be if you code was a library
of some sorts and other developers had to use it. In a
inherited class, you have public visibility to the constructor
or some other method, and then suddenly in the descendant class
the methods are hidden from the developer?? Not a good idea.
==============================================================
I don't understand this, because to me, the VER-1 constructor is
introduced in TDerived, make it non-public does NOT reduce the
visibility of VER-0 constructor, hence is not a violation of
visibility rules, is it???
Thanks!
Xiangrong
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20131025/2a656b43/attachment.html>
More information about the fpc-pascal
mailing list