Instances of classes always updating

Alright, so usually, when you have two variables, e.g. int i1 and int 2, and then you set i1 equal to i2 and change i2, the value in i1 stays put.
int i1 = 5; int i2 = i1; i1 = 3; println(i1); //would print 5
But now if you do the same thing but with instances of a class, something different happens. When setting one instance of it to another and then updating the other one, the first one also updates. This can be demonstrated with:
cInt i1 = new cInt(5); cInt i2 = i1; i1.value = 3; println(i2.value); //now prints 3 class cInt { int value; cInt(int input) { value = input; } }
In order to avoid that, you’d have to write i1 = new cInt(3); instead of i1.value = 3;, which, while easy in this case, would be far too complicated when dealing with bigger, more complex classes.

Can anyone please explain why that is and provide a solution?

2 Likes

A primitive explanation:

when you say = with the initial object, both objects just refer to the same memory address, so they are connected and have always the same value.

To avoid this, use new for the 2nd object.

Then copy the value into the new variable.

You can also make a function within the class eg name copy() with its return type being cInt and use new there and fill the new object with the data and return it. Then the hassle is inside the function and it’s clean from the outside.

then you can say

i2= i1.copy();

1 Like

Remark: useful convention: every class begins with a Capital Letter

Yeah right, I have that in the actual code I’m working on

1 Like

I’ve tried it for the example sketch with cInt and it worked, but in my actual project, it somehow doesn’t. I’ll just keep on searching…

It doesn’t work?

Did try to make the function copy() inside the class:

cInt copy () {

cInt newObject = new cInt(0);

newObject.value = value; 

return newObject;

}

It did work for the cInt class just like in your example, but not in the code I’m actually working on. However, i’ve already found a different solution. Anyways, thank you for your help

1 Like

The principle of the function copy() should always be the same.

Of course one needs to get all relevant values into the new object before returning it