Reputation: 24555
I have just started to use D language and I was trying out some object-oriented code.
I am trying following code:
import std.stdio;
class Testclass{
private int intvar = 5;
private string strvar = "testing";
}
void main(){
auto tc = new Testclass();
// check if private variables are accessible:
writeln(tc.intvar);
writeln(tc.strvar);
}
Running above code has following output:
$ rdmd soq_private.d
5
testing
I find that intvar and strvar variables are accessible from main fn. Should they not be inaccessible if they are declared private in their class?
Upvotes: 1
Views: 61
Reputation: 143
From the D spec:
- Symbols with private visibility can only be accessed from within the same module.
https://dlang.org/spec/attribute.html#visibility_attributes
So private applies module-wide, not class-wide. D does not have an aggregate-only visibility attribute.
Upvotes: 0
Reputation: 2879
See the "D Lang" Wiki:
"Private means that only members of the enclosing class can access the member, or members and functions in the same module as the enclosing class. Private members cannot be overridden."
https://wiki.dlang.org/Access_specifiers_and_visibility
Since you are in the same module as the enclosing class, this is allowed.
Upvotes: 2