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

Neia Neutuladh neia at ikeran.org
Mon Oct 29 16:25:29 UTC 2018


On Mon, 29 Oct 2018 05:13:08 +0000, unprotected-entity wrote:
> On Sunday, 28 October 2018 at 11:32:07 UTC, Mike Parker wrote:
>>
>> In D, the module is the unit of encapsulation, not the class.
> 
> Again. this is not entirely correct.
> 
> -----
> class Foo { private int i; }
> 
> void main()
> {
>   {Foo f;}
>   f.i++;
> }
> 
> ----
> 
> It's really hard to have a converstation when posts are being checked by
> 'someone', at 'their leisure', before (or if) they ever get posted??

There are two concepts here: scope and encapsulation. This is a 
demonstration of scope. A variable that is not in scope might point to 
data that doesn't currently exist, or there might simply be no way to 
refer to that data in an unambiguous way.

In your example, an optimizing compiler might have destroyed `f` and 
reclaimed its memory at the end of its block.

A related example shows the ambiguity as well:

---
class Foo { private int i; }
void main()
{
  {Foo f = new Foo;}
  {Foo f = new Foo;}
  f.i++;
}
---

Similarly with your function example, there's no general way to refer to 
variables in other functions. Your function can't know where it's called 
from, so it can't refer to variables higher up on the stack. Variables that 
are lower down on the stack have already been destroyed. Plus with 
recursion, you can't specify which copy of a variable you're talking about.


More information about the Digitalmars-d mailing list