Why does the following program not output the same result for both function calls?
#include<iostream>
using namespace std;
class Test {
private:
int x;
int y;
public:
Test (int x = 0, int y = 0) { this->x = x; this->y = y; }
Test setX(int a) { x = a; return *this; }
Test setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main() {
Test obj1;
obj1.setX(10).setY(20).print();
obj1.print();
return 0;
}
I assumed that it’s a shallow copy so changes made to it should also be reflected in the original object. If it’s a deep copy then the result of the print method call makes sense.
object 1's internal modified copy has its y set to 20 and that one's internal copy is printed.
this is different from object 1, which did not get updated from what was done to the internal copies.
all you ever did to object 1 was set x = 10. the rest of it affects other objects.
Differentiating "deep" and "shallow" copies only makes sense in the context of copying pointers or other handles to resources. For "trivial" objects that don't contain pointers or handles to resources, you can think of everything as being a deep copy.
Yes, the internal copies of obj1 are deleted (destructed) after the chained function call line, but that doesn't really have anything to do with why setY(20) didn't affect the original object.
Simply put, the call to setY(20) only changed a copy of your object, and not the original object. It doesn't matter when that internal object was deleted.
What do you mean by handles to resources?
Don’t the objects being copied in this scenario contain (this) pointers?
What are common examples of trivial and non-trivial objects?
Don’t the objects being copied in this scenario contain (this) pointers?
No. Instead, the implicit object ("*this") is an inherent property of object identity.
We aren't typically concerned with object identity. Instead, we're typically concerned with the values that an object represents. This focus on values (what's called value semantics) is mostly the default for C and C++ programs. It's a major source of strength for both languages. https://en.wikipedia.org/wiki/Value_semantics
What's happening here is that the entire value representation is copied. There's no shared representation of the value of a class - and no need to call some clone() method to duplicate it.