# 9.6 Copies, references and identity

> Assigning an object does not duplicate it: it gives another name to the same object. To get a new object with the same data you need `Copiar`.

Web page: https://pseudolearn.app/en/spec/objetos/copia

> **In one sentence**
>
> Assigning an object does not duplicate it: it gives another name to the same object. To get a new object with the same data you need `Copiar`.

## 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.

### Program: An alias and a copy

```pseudolearn
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;
EndAlgorithm
```

**Output**

```text
5 5 9
true false
```

*The program finishes normally.*

**Figure 9.6-1: Alias versus copy**

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.

`a` and `alias` point to the same object; `copia` points to another one with the same data at first.

1. Step 1: `alias <- a` creates nothing: two arrows to the same object.
2. Step 2: `Copiar(a)` creates a second object with the same values.
3. Step 3: Changing `alias.libros` is visible through `a`; changing `copia.libros` is not.

## 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.
- `Copiar` creates a new object and copies a single level.
- Identity is the creation order and is never reused.
- `=` between objects compares identity, not contents.

**See also**
- [9.1 Classes and attributes](https://pseudolearn.app/en/spec/objetos/clase.md)
- [7.2 Parameters](https://pseudolearn.app/en/spec/subprogramas/parametros.md)
- [13.2 Memory and the collector](https://pseudolearn.app/en/spec/motor/memoria.md)
