Why do private member variables behaved like protected in the same module when creating deriving class?
biozic
dransic at gmail.com
Mon Oct 29 20:15:36 UTC 2018
On Monday, 29 October 2018 at 09:15:35 UTC, unprotected-entity
wrote:
> On Monday, 29 October 2018 at 08:34:39 UTC, FeepingCreature
> wrote:
>> Yes they do.
>> ---
>> module test;
>> import std.stdio;
>> class C { int a; }
>> void main() { writeln(a); } // Error: undefined identifier 'a'
>
> Sorry, but you are wrong.
>
> Why? Because 'a' is nothing - it does not even exist. Not
> anywhere.
Yes, it does exist as a symbol :
---
import std.stdio;
class C { int a; }
void main() { writeln(typeof(C.a).stringof); }
---
> To make it exist, you need to instantiate an object of C.
No, see code above. Of course you would need to instantiate C to
*use* it. But you would also need to call your test function to
use its variable a.
> Once it actually 'exists', you can do whatever you like with
> it, in the module, regardless of its access modifier. That
> means, quite simply, that the class is not a unit of
> encapsulation - within the module. Outside the module it is,
> but inside, it is not.
Yes, exactly. These are the official D rules.
> That is just fact. It's not something we should be arguing
> about - cause it's just a fact.
>
> On the otherhand, a function (unlike a class) within a module,
> still retains it's encapsulating properties.
>
> i.e.
> void test() {int a;};
> void main() {a++;}; // Error: undefined identifier 'a' - but
> this time, 'a' does exist - it's just that its correctly
> encapsulated in the function.
You're confusing the existence a symbol and the path to access
it. While there is a way to point to the field name 'a' in class
'C' in the code above (i.e `C.a`), there is no way to point to
the variable 'a' in function test. So these are not encapsulation
differences. Encapsulation is about whether or not you can use a
symbol that you can point to with the correct syntax in the first
place.
> Just imagine if a function did not have those encapsulating
> properties.
>
> Now, just imagine if a class did not (well, you don't need to
> imagine it ;-)
>
> I'm not trying to argue here. I'm just trying to clarify a
> fact, that some seem unable, or unwilling, to accept.
Not clarified for me ;)
Though I agree with you that there could be a `class private`
access modifier in D for your use case.
More information about the Digitalmars-d
mailing list