having fun with code

Copying objects vs. copying references

C++ is a language that allows creation of static instances of objects, this is without using pointers. This is why copy-constructors are needed, since it is common to copy or clone objects. Other languages like Delphi don’t allow to create static variables to instantiate objects. Instead, all objects are pointers. So in C++, assignments of instances of the same class create a copy of the object, while in Delphi, only the reference to the second instance is copied.

When I started learning Python one year ago, I wanted to know if objects were cloned on assignments or if only the reference to the object was assigned instead. Here is how I found it:

  1. class Item():
  2.   def __init__ (self):
  3.     self.text = ""
  4.   def sayIt(self):
  5.     print self.text
  6.  
  7. A = Item()
  8. B = Item()
  9. A.text = "testing A"
  10. B.text = "testing B"
  11. A.sayIt()
  12. B.sayIt()
  13. A = B
  14. A.sayIt()
  15. B.sayIt()
  16. A.text = "testing A 2"
  17. A.sayIt()
  18. B.sayIt()

This code will output 6 messages. The first two will be obviously different, since A and B are to separate instances on memory. When B is assigned to A, two things can happen. B is cloned and A is a new instance equal to B or the reference to B is assigned to A so A and B become the same instance in memory (B). No matter which one happens, both messages after the assignment will correspond to the B instance (“testing B”).

But what will happen when we modify A again? Will B be also modified?

Here is the output:

testing A
testing B
testing B
testing B
testing A 2
testing A 2

So A and B are now the same object in memory.

Related Posts:

2 Comments to Copying objects vs. copying references

  1. December 1, 2008 at 03:16 | Permalink

    It reminds me about Politecnica ;). By the way, will you come on Christmas? Too much time since I last saw the two of you…

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info

PromoteJS

JavaScript JS Documentation