www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - private attribute don't function?

reply "Zhouxuan" <pycerl qq.com> writes:
import std.stdio;

class A
{
	private int j = 1;
	
	private
	{
		int k = 2;
	}
	
private:
	int i = 0;
}

void main()
{
	A a = new A;
	writeln(a.i);
	writeln(a.j);
	writeln(a.k);
}

It compiles and output 0 1 2 repectively.
Oct 05 2013
next sibling parent "David Nadlinger" <code klickverbot.at> writes:
On Saturday, 5 October 2013 at 15:19:34 UTC, Zhouxuan wrote:
 import std.stdio;

 class A
 {
 	private int j = 1;
 	
 	private
 	{
 		int k = 2;
 	}
 	
 private:
 	int i = 0;
 }

 void main()
 {
 	A a = new A;
 	writeln(a.i);
 	writeln(a.j);
 	writeln(a.k);
 }

In D, "private" means "private to the current module". If you try accessing the fields from another module, you'll see that it doesn't work. In the future, please consider posting similar question in digitalmars.D.learn. David
Oct 05 2013
prev sibling next sibling parent "Adam D. Ruppe" <destructionator gmail.com> writes:
http://dlang.org/attribute.html

"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. 
Private module members are equivalent to static declarations in C 
programs. "

In D, private is only hidden to different modules. If it is in 
the same module, they can see it anyway.
Oct 05 2013
prev sibling parent "Zhouxuan" <pycerl qq.com> writes:
On Saturday, 5 October 2013 at 15:21:46 UTC, David Nadlinger 
wrote:
 On Saturday, 5 October 2013 at 15:19:34 UTC, Zhouxuan wrote:
 import std.stdio;

 class A
 {
 	private int j = 1;
 	
 	private
 	{
 		int k = 2;
 	}
 	
 private:
 	int i = 0;
 }

 void main()
 {
 	A a = new A;
 	writeln(a.i);
 	writeln(a.j);
 	writeln(a.k);
 }

In D, "private" means "private to the current module". If you try accessing the fields from another module, you'll see that it doesn't work. In the future, please consider posting similar question in digitalmars.D.learn. David

Okay, got it, thank you!
Oct 05 2013