Copying Data Instead of Memory Addresses

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am currently trying to work on a program and I found it more convient to
have a tempory object which would hold a copy of data loaded from a file so I
wouldn't have to work with the overhead of loading from a file repeatedly.
My problem is that when I store the temporary object to another object,
changing the temporary object or its data also changes the data of the other
object.

Example:

MyClass a=new MyClass(2), b=new MyClass(3);
b=a;
a.data=10;
//b's data field now also equals 10 although what I really wanted to do was
//copy the integer data and keep it the same even if a's data field changed.

Since my objects are more complex than just one integer, I don't want to
have to manually move all the data and since there are also some objects
(such as Bitmaps) in the temporary object, so I would be unable to move the
data by hand without incurring the error described above.

Is there any way to create a copy of one object in such a way that the data
of the copy is not changed when the data of the original is changed?

Thank you.
 
This is how it should be. Look at what you are doing.

Here create a pointer to a class and call that pointer "a" and create and
object that "a" now points to.
MyClass a=new MyClass(2),

Here create a pointer to a class and call that pointer "b" and create and
object that "b" now points to.
b=new MyClass(3);

now have b point to the same object a and forget all about the object b
pointed to.
b=a;
a.data=10;

You have to make a copy of "a" in order to do what you want.

MyClass a, b
a = new MyClass(2)
b = a.makecopy()

hope this helps
Chris
 
You want your class to implement the ICloneable interface.

You can then copy the object by saying

MyClass b = a.Clone();

However, you do have to write Clone() yourself, and define what
"cloning" means for your class....
 
You want your class to implement the ICloneable interface.

You can then copy the object by saying

MyClass b = a.Clone();

However, you do have to write Clone() yourself, and define what
"cloning" means for your class....
 
Back
Top