Class member always has the same address

szymski via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Mar 19 13:24:15 PDT 2016


Hello!
I'm having a big problem with class members. I'm kinda new to D, 
so this may be my fault, but look at the following code:

>import std.stdio;
>
>class B {
>	int variable;
>}
>
>class A {
>	B b = new B();	
>}
>
>void main()
>{
>	// Create 10 instances of A
>	foreach(i; 0 .. 10) {
>		auto a = new A();
>
>		writeln(&a.b.variable, " = ", a.b.variable); // Print 
>a.b.variable address and its value 		a.b.variable++;
>	}
>}

When ran, it prints something totally different from what I 
expect:

>430088 = 0
>430088 = 1
>430088 = 2
>430088 = 3
>430088 = 4
>430088 = 5
>430088 = 6
>430088 = 7
>430088 = 8
>430088 = 9

In my opinion &a.b.variable should give different addresses for 
each instance of A, because it's not static. What am I doing 
wrong? Thanks in advance.



More information about the Digitalmars-d-learn mailing list