Aliasing example, try to understand this issue

248 Views Asked by At

I try to learn about Aliasing and encounter this example:

public class A
{
    // Instance variable 
    private double _x;

    // 3 constructors 

    public A(double x)
    {
        _x = x;
    }

    public A()
    {
        _x = 0;
    }

    public A(A a)
    {
        _x = a._x;
    }

    // methods 
    public double getX()
    {
        return _x;
    }

    public void setX(double x)
    {
        _x = x;
    }

    public String toString()
    {
        return "A:" + _x;
    } 
}

static void Main(string[] args)
{
    A a1 = new A(7);
    A a2 = new A(a1);
    A a3 = a2;

    Console.WriteLine("a1 = " + a1.toString());
    Console.WriteLine("a2 = " + a2.toString());
    Console.WriteLine("a3 = " + a3.toString());

    a1.setX(10);
    Console.WriteLine("after setting 10 to a1:");
    Console.WriteLine("a1 = " + a1.toString());
    Console.WriteLine("a2 = " + a2.toString());
    Console.WriteLine("a3 = " + a3.toString());

    a3.setX(5);
    Console.WriteLine("after setting 5 to a3:");
    Console.WriteLine("a1 = " + a1.toString());
    Console.WriteLine("a2 = " + a2.toString());
    Console.WriteLine("a3 = " + a3.toString());

    Console.ReadLine();
}

The first Console.WriteLine and the first SetX is clrea but why after a3.setX(5), also a2 changed ? According the declaration A a3 = a2 and SetX refer to a3

1

There are 1 best solutions below

3
On

Both a2 and a3 are references¹ to the same object. Since you have one object (and two references to it), changing the object by means of any reference will produce changes visible, again, by means of any reference.


¹ Reference here is Java jargon for what in C/C++ is called pointer. And your example will show the same behaviour when you have pointer aliasing in those languages.