9.6.1 How it works
Not all values behave the same when assigned:
| Value | When assigned or passed by value |
|---|---|
| numbers, booleans, characters and texts | copied: changing the source does not affect the copy |
| objects | shared: both names see the same object |
| arrays | passed by reference |
Copiar(object) creates a new object of the same class without running the constructor, and copies a single level: primitive attributes are copied, and those that are references stay shared with the original.
ProgramAn alias and a copy
Class Mochila
Define dueno As String;
Define libros As Integer;
EndClass
Algorithm Copias
Define a As Mochila <- New Mochila();
a.dueno <- "Ana";
a.libros <- 3;
Define alias As Mochila <- a;
Define copia As Mochila <- copy(a);
alias.libros <- 5;
copia.libros <- 9;
Write a.libros, " ", alias.libros, " ", copia.libros;
Write a = alias, " ", a = copia;
EndAlgorithmOutput
5 5 9 true false
The program finishes normally.
1
alias <- acreates nothing: two arrows to the same object.2
Copiar(a)creates a second object with the same values.3Changing
alias.librosis visible througha; changingcopia.librosis not.
a and alias point to the same object; copia points to another one with the same data at first.a and alias point to object 1 with owner Ana and 3 books. Copiar creates object 2 with the same data, pointed to by copia. Afterwards object 1 has 5 books and object 2 has 9.
9.6.2 Identity
Every object or array has an identity: the order number in which it was created during the run. The first is 1, the next 2, and so on. Identity never changes and is never reused, even after the object is no longer used. = between objects compares identities: that is why a = copia is False even though they hold the same data.
Reference cycles —an object pointing to another that points back to the first— are valid.
In short
- Primitives and texts are copied; objects are shared.
Copiarcreates a new object and copies a single level.- Identity is the creation order and is never reused.
=between objects compares identity, not contents.