I am a beginner, and I wonder about the following.
Let's say I have a class foo
and created an object foo first
and put some data into it:
foo first = new foo();
first.data="mydata";
I then want to create another object foo second
and make it have the same contents (but not identical memory location) as first
. Can I do the following to achieve that?
foo second = new foo();
second = first;
Or does this just set first
and second
to the same memory address and I just effectively obtain two handles on a single object in memory?
I read about cloning of objects and it seems way too complicated. I feel like since I went through the trouble of defining a new foo
in foo second = new foo();
the compiler should realize that second = first;
intends to copy the entire thing and not just point to the first one. Is that how it works?
So my question is: Why is this not how this works? What is the flaw in the above logic of having the compiler set up like that?