C
C#2w ago
tommy

✅ 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
Lê Duy Quang
Lê Duy Quang2w ago
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.
tommy
tommy2w ago
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?
Lê Duy Quang
Lê Duy Quang2w ago
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.
tommy
tommy2w ago
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?
Lê Duy Quang
Lê Duy Quang2w ago
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.
tommy
tommy2w ago
do we not know what the compiler is doing exactly?
Lê Duy Quang
Lê Duy Quang2w ago
It's not related to the compiler.
tommy
tommy2w ago
okay
Lê Duy Quang
Lê Duy Quang2w ago
It's the code in that constructor.
tommy
tommy2w ago
oh yeah of course then assume that we have created a copy constructor i should have mentioned
Lê Duy Quang
Lê Duy Quang2w ago
Still, it's up to that constructor what kind of copy it is.
tommy
tommy2w ago
that is interesting say we have something like this
public class MyClass {
string name;
public MyClass(MyClass obj) {
name = obj.name;
}
}
public class MyClass {
string name;
public MyClass(MyClass obj) {
name = obj.name;
}
}
Lê Duy Quang
Lê Duy Quang2w ago
This can be sufficiently regarded as a deep copy because string is immutable.
tommy
tommy2w ago
ohkay
public class MyClass {
int num;
public MyClass(MyClass obj) {
num = obj.num;
}
}
public class MyClass {
int num;
public MyClass(MyClass obj) {
num = obj.num;
}
}
what about this
Lê Duy Quang
Lê Duy Quang2w ago
Is int mutable?
tommy
tommy2w ago
yup
Lê Duy Quang
Lê Duy Quang2w ago
How?
tommy
tommy2w ago
doesn't it get changed in the memory location upon a new assignment
Lê Duy Quang
Lê Duy Quang2w ago
That's putting a brand new value into the field. int here is a value type, not mutable.
tommy
tommy2w ago
my basics are really bad thanks man I'll figure things out
Lê Duy Quang
Lê Duy Quang2w ago
My advice is then don't skip lessons.
tommy
tommy2w ago
sure i have never been learning things on my own
Lê Duy Quang
Lê Duy Quang2w ago
I mean follow a proper course.
tommy
tommy2w ago
ohkay time to work
Want results from more Discord servers?
Add your server