Module-level accessibility

Jonathan M Davis jmdavisProg at gmx.com
Tue Oct 5 17:27:58 PDT 2010


On Tuesday 05 October 2010 09:42:14 Steven Schveighoffer wrote:
> And when would a protected hook be callable from an unknown/uncontrolled
> context?  In whose eyes, the base or derived class?
> 
> The thing is, any class that defines a private function implementation is
> able to call it.  You can't prevent that.  So in the eyes of any base
> class, it has no way to restrict that.  In the eyes of the derived class,
> it has no control over whether a base class can call it or not.
> Essentially a private overridable function has one additional guarantee
> over a protected function -- a derived class cannot call it if it hasn't
> defined its own version (and isn't in the same module).  But that's not
> the property desired, the property desired for NVI is that *nobody* can
> call it except the base class, even derived classes.  That's simply not
> possible.  So we have to pretend that we can't call it, which is fine,
> just as easy with protected.
> 
> Consider this:
> 
> abstract class A
> {
>    public void myAPIFn() { foo(); }
>    abstract private void foo();
> }
> 
> abstract class B : A
> {
>    public void bar() {myAPIFn();}
> }
> 
> class C : B
> {
>    private void foo() {}
> }
> 
> So good so far.  But I can alter B so it can circumvent myAPIFn by adding
> its own implementation for foo (which does nothing), and now I'm able to
> call foo directly from myAPIFn.  Basically, even though B does not intend
> for its version of foo to be the real implementation (knowing that it's
> abstract and must be derived), it can hijack A's ability to funnel all
> calls through myAPIFn by simply adding a blank function.
> 
> I just don't see the benefit over protected anywhere.  You can't say
> "you're allowed to define this, but you're not allowed to call it."  That
> makes no sense at all, and as I've shown, is impossible to enforce.

Well, I don't see why it wouldn't be possible for the compiler to enforce that 
overridden private methods can't be called by anyone but the base class. That 
being the case, then allowing for private virtual functions is most definitely 
useful. However, if it really isn't possible to restrict it so that derived 
classes can't call the private methods that they've overridden, then I do agree 
that we might as well just stick to using protected and make private functions 
unoverridable. But if we _can_ make it so that derived classes can't call 
overridden private methods, I think that that would be valuable and desirable.

- Jonathan M Davis


More information about the Digitalmars-d mailing list