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.