Private Nested Classes?
Rémy Mouëza
remy.moueza at gmail.com
Sun Mar 31 20:58:11 UTC 2019
On Sunday, 31 March 2019 at 20:07:39 UTC, D Man wrote:
> Is it possible to have private inner nested classes?
>
> For example if I have a class that is only ever used inside
> another class, it would make sense to be able to 'lock' it
> inside the outer class, so that raw instances of it cannot be
> created.
>
> But in this example: https://run.dlang.io/is/PfemUV
>
> The `private` specifier seems to have no meaning.
>
> Is there a way to get the desired effect (make a nested class
> only accessable from within it's outer class)?
In D the unit of encapsulation is the module, not the class.
As the main function resides in the same module as the A.Inner
class, it is visible and no compiler error should occur.
This rules is meant as a simplification of C++ friend classes and
functions. In D, instead of defining friends, one put related
class and function into the same module.
To "lock" the class, we need separate the main function from
class A. This gives a warning (using dmd v2.085.0):
main.d(7): Deprecation: a.A.Inner is not visible from module main
I notice that Inner is defined as "private static", meaning that
you don't intend to use any reference to the enclosing class
through `this.outer`.
By putting Inner outside of class A, and having main outside of
the module, an error occurs:
main.d(7): Error: module `main` class a.Inner is private
main.d(7): Deprecation: a.Inner is not visible from module main
More information about the Digitalmars-d
mailing list