Why are class variables public, when marked by the 'private' keyword?

Mike Parker aldacron at gmail.com
Sat Mar 21 04:58:32 UTC 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.



More information about the Digitalmars-d-learn mailing list