Why do private member variables behaved like protected in the same module when creating deriving class?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun Oct 28 05:11:06 UTC 2018


On Saturday, October 27, 2018 10:38:53 PM MDT unprotected-entity via 
Digitalmars-d wrote:
> On Saturday, 27 October 2018 at 18:06:36 UTC, Atila Neves wrote:
> > On Saturday, 27 October 2018 at 15:24:19 UTC,
> >
> > unprotected-entity wrote:
> >> On Saturday, 27 October 2018 at 14:20:10 UTC, Steven
> >>
> >> Schveighoffer wrote:
> >>> If b didn't have an `x` in it, then how would this work?
> >>
> >> Only in D, does b have x in it.
> >>
> >> In C++, Java and C#, b does *not* have x in it.
> >
> > It might be that you're confusing "have" to mean "has access".
> > In other languages b doesn't have access to x, but it most
> > definitely has an x inside of it.
>
> In C++/Java/C#, x is private to C, as you would expect, since it
> was declared private to C.
>
> In D, it's not private to C, or anything else in the same module.
>
> I know the reasoning behind this, but it's just awful, and
> invites bugs into your code.
>
> oh... so you accidently typed b.x++ in main().. or someother code
> outside of the class), instead of b.increment() ...well...to bad.
>
> Yes.. it's an old discussion, I know..but an unprotected entity
> is a useless programming construct, and will invite bugs into
> your program.

LOL. I have no clue how you just accidentally use a member variable. But if
that's a concern, it's exactly the same concern that you would have in C++
or Java from within a functions inside a class that you don't want accessing
a particular member variable. D just puts the demarcation line at the module
instead of the class. It doesn't really change much ultimately in terms of
needing to being aware of what is supposed to be accessed where for anything
that has access. And if you want to further restrict access, then put
classes in their own modules. Problem solved. Some of the languages that
define private the way that some folks want already require that anyway.
Honestly, I have _never_ seen a bug caused by the fact that D makes private
restrict access to the module level and not the class or struct level. From
everything I've seen, this is entirely an issue of people not liking the
idea and not something that's an actual problem in practice.

- Jonathan M Davis





More information about the Digitalmars-d mailing list