Processing bug - setting A (object) to B (object) and modifying A, it will change B too!

Hello everyone!
There is an issue with PVectors and objects.
If you do this:

PVector a = new PVector(0,0);
PVector b = new PVector(100,100);
PVector c = a;
println(a,c); //prints [ 50.0, 50.0, 0.0 ] [ 50.0, 50.0, 0.0 ]

lerp will effect both a & c. The same happens with objects. Is this a bug or a feature. Feels more like a bug. Thank you!

EDIT: I know objects are saved as strange letter sequences but still

In the case above variable c is assigned w/ the same reference (memory address) value as variable a.

Therefore they’re both alias to the same PVector object.

If you don’t want c to be an alias clone a before assigning it to c using method copy() or get():
PVector c = a.get();


PVector is inbuilt

But when I have my own class

Do i have to program a own copy function or is there
an automatical function?

1 Like

It’s an interesting question, @Chrisir, with a complicated answer. If your class contains references to other classes, or attributes that should be unique to each instance, you will need to define what constitutes a clone for that class, and then implement it as code.

For example, suppose you define a Car class. If you copy an instance of a Car, should all its attributes be identical, or should you give the copy its own vehicle identification number?

You will also need to decide whether if the Car was made in a Factory, you need to copy the Factory instance, as opposed to referencing the same one associated with the original Car instance.

EDIT (August 8, 2021):

For an overview of the issues, see Wikipedia: Object copying. Then do some Googling. There are deep copies, shallow copies, and combinations.

Getting back the Car example, suppose we also have a Dealer class. The Car instance was bought at a Dealer instance. Every so often, the Car drives itself to the Dealer to get serviced.

A copy of the Car should probably share the same Dealer instance reference as the original, rather than have its own copy of the Dealer. Let’s say the Dealer instance reconfigures its facility, so that the Car, which is self-driving, needs to drive itself to a different garage door for future servicing. With all copies of the Car referencing the same Dealer instance, a change to that single Dealer can communicate the change to all pertinent Car instances. This would be better than having multiple copies of the Dealer instance, and is an aspect of making a shallow copy of the Car. In actuality, copying a Car would likely involve a combination of deep and shallow copying. Real cars share real dealers, but each one gets its own engine.

1 Like