Thread overview
Why are class variables public, when marked by the 'private' keyword?
Mar 21, 2020
Kirill
Mar 21, 2020
Mike Parker
Mar 21, 2020
Kirill
March 21, 2020
I was playing around with visibility attributes in D. I created a class with private variables. Then I tried to access those variables through the class object. It compiled without any errors. However, ...

Shouldn't the compiler output an error for trying to access private members of a class? Do I get something wrong?

Here is the code:

import std.stdio;

class ID {
public:
     int id = 3849493;
private:
     string name = "Julia";
     int age = 17;
};

void main() {
     ID p = new ID();

     writeln(p.name, " ", p.age, " ", p.id);
}



March 21, 2020
On Saturday, 21 March 2020 at 04:45:29 UTC, Kirill wrote:
> I was playing around with visibility attributes in D. I created a class with private variables. Then I tried to access those variables through the class object. It compiled without any errors. However, ...
>
> Shouldn't the compiler output an error for trying to access private members of a class? Do I get something wrong?
>
> Here is the code:
>
> import std.stdio;
>
> class ID {
> public:
>      int id = 3849493;
> private:
>      string name = "Julia";
>      int age = 17;
> };
>
> void main() {
>      ID p = new ID();
>
>      writeln(p.name, " ", p.age, " ", p.id);
> }

In D, the unit of encapsulation is the module. So private means "private to the module", i.e., private members are accessible within the same module. If ID were in a different module from main, you would see an error.

March 21, 2020
On Saturday, 21 March 2020 at 04:58:32 UTC, Mike Parker wrote:
> In D, the unit of encapsulation is the module. So private means "private to the module", i.e., private members are accessible within the same module. If ID were in a different module from main, you would see an error.

Indeed, I read something like this somewhere... It makes sense to me now! Thank you!