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

Mike Parker aldacron at gmail.com
Sat Oct 27 03:20:43 UTC 2018


On Friday, 26 October 2018 at 22:01:42 UTC, 12345swordy wrote:
> On Friday, 26 October 2018 at 21:46:27 UTC, Laurent Tréguier 
> wrote:

>> You simply seemed to be implying that private had the same 
>> effect as protected, which isn't the case.
> ... How can I make my self any more clear here!? When I say y 
> behaves like x it I don't means y is exactly the x! Nor does it 
> imply that!

Here's the example code from your issue #19334:

```
import std.stdio;
class A
{
     private int y;
}

class B : A
{
};

void main()
{
     B b = new B();
     b.y = 1; // Should be a compile error as class shouldn't have 
private int y.
     writeln(b.y);
}
```

First, this really is about encapsulation and *not* inheritance. 
Even if class B is in another module, it would still inherit y, 
i.e. it would have its own copy of y. private working as intended.

Second, A, B, and main are in the same module. The spec clearly 
says that everything in the same module has access to private 
members. I quoted it in the bug report and it's been quoted two 
or three times here. So main has access to y.

If used to be that even if you moved the declaration of B to 
another module, then main would still have access to y through b. 
That was deemed to be a bug an is now deprecated. But as long as 
they are all in the same module, it's working as intended.




More information about the Digitalmars-d mailing list