✅ difference between `MyClass obj2 = obj1;` and `MyClass obj2 = new MyClass(obj1);`
I am learning copy constructors and trying to know how to create shallow and deep copy constructors.
24 Replies
That has little to do with shallow or deep copy.
One just makes the variable hold the same instance as the original and one makes a new instance with the original as an argument.
okay
so the first one creates a new name for the already created object
and the second one is copying field in a new location?
is that it?
It's not a name, it's a variable whose value is a reference to that instance.
The second one makes a new instance, what the constructor does isn't known, it may be trying to copy, or it may be doing something else.
so the first copies the reference, or address, and points to the same instance
the second one creates a new instance with the previous instance's values copied
sorry bro I am just a noob
one small thing, i think the second one creates a shallow copy.
how to create a deep copy?
Again that code isn't related to copying.
what the constructor does isn't known, it may be trying to copy, or it may be doing something else.
do we not know what the compiler is doing exactly?
It's not related to the compiler.
okay
It's the code in that constructor.
oh yeah of course
then assume that we have created a copy constructor
i should have mentioned
Still, it's up to that constructor what kind of copy it is.
that is interesting
say we have something like this
This can be sufficiently regarded as a deep copy because
string
is immutable.ohkay
what about this
Is
int
mutable?yup
How?
doesn't it get changed in the memory location upon a new assignment
That's putting a brand new value into the field.
int
here is a value type, not mutable.my basics are really bad
thanks man
I'll figure things out
My advice is then don't skip lessons.
sure
i have never
been learning things on my own
I mean follow a proper course.
ohkay
time to work