www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why are class variables public, when marked by the 'private' keyword?

reply Kirill <kirill.saidov mail.com> writes:
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);
}
Mar 20 2020
parent reply Mike Parker <aldacron gmail.com> writes:
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.
Mar 20 2020
parent Kirill <kirill.saidov mail.com> writes:
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!
Mar 20 2020