Confused about class equality
Ali Çehreli
acehreli at yahoo.com
Sat Apr 3 16:27:25 PDT 2010
strtr wrote:
> The program below outputs, as I would expect :
> Same Value.
> Same Object.
> 3 : 44E15C 0000
> 3 : 44E15C 0000
> 5 : 44E15C 0000
> 5 : 44E15C 0000
>
> Now what would it mean if it were to output :
> Same Value.
> 3 : 5B536C 59D020
> 3 : 59CE0C 59CEF0
> 5 : 5B536C 59D020
> 5 : 59CE0C 59CEF0
> (Output from essentially the same piece of code within a larger project)
>
> Not the same object, but still able to change it with one call.
> What is it I don't get?
>
> ------
> module main;
>
> import std.stdio;
> import std.string;
>
> interface I{
> char[] toString();
> int value();
> void value(int v);
> }
>
> class C : I{
> private int _value;
>
> this(int v){ _value = v; }
> char[] toString(){ return format(_value); };
> int value(){ return _value; };
> void value(int v){ _value = v; };
> }
> private I[3][3] arr;
>
> public I getI( int x, int y){ return arr[x][y]; }
> public void setI( int x, int y, I i ){ arr[x][y]= i; }
>
> void main(){
> C c = new C(3);
> setI( 0, 0, c );
> setI( 1, 2, c );
> I i1 = null;
> I i2 = null;
> i1 = getI(0,0);
> i2 = getI(1,2);
>
> if( i1 !is null && i2 !is null && i2.value == i1.value ) {
> writefln("Same Value.");
> if( i2 is i1 ) writefln("Same Object.");
> writefln( i2.toString()," : ",i2.__vptr," ",i2.__monitor);
> writefln( i1.toString(), " : ", i1.__vptr," ",i1.__monitor);
> i1.value = 5;
> writefln( i2.toString()," : ",i2.__vptr," ",i2.__monitor);
> writefln( i1.toString(), " : ", i1.__vptr," ",i1.__monitor);
> }
> }
The code works as expected with 2.042
I had to modify the toString() functions to return string, and say
"override" in C's toString definition; and had to modify the writefln()
calls:
writefln("%s : %s %s", i2.toString(), i2.__vptr, i2.__monitor);
The output:
Same Value.
Same Object.
3 : 806D3F4 0
3 : 806D3F4 0
5 : 806D3F4 0
5 : 806D3F4 0
Ali
More information about the Digitalmars-d-learn
mailing list