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

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Oct 27 21:03:57 UTC 2018


On Saturday, October 27, 2018 12:06:36 PM MDT Atila Neves via Digitalmars-d 
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.

And depending on the language, you can even give access to them - e.g. in
C++, friends could be used to give access, though it would be a bit odd,
since normally you'd just used protected for such a use case rather than
making the derived class a friend. Either way, Derived classes _are_ base
classes and literally contain their base class members. They wouldn't work
when used via a pointer of the base class type otherwise. So, yeah, it's a
question of having access and not whether they're there. They have to be
there. The combination of D's private being private to the module, not the
class, and putting the derived class in the same module as the base class
simply creates a situation that you wouldn't normally get in other languages
with regards to access. The layout of the class itself should actually be
very similar to what you'd get in C++, Java, C#, etc. Each language may have
minor differences in how it actually lays out classes, but the fact that a
base class is physically part of a derived class is common to all of them,
and unless the language requires that all base classes be pure interfaces, I
don't see how it could possibly be otherwise.

- Jonathan M Davis





More information about the Digitalmars-d mailing list