I'm learning C++ and there is something I don't get about assignment operators. As far as I understand, they are supposed to provide deep copies of object. Here is an example
Test::Test(int i){
value = i;
}
Test& Test::operator=(const Test& rhs){
value = rhs.value;
return *this;
}
Now:
Test* t1 = new Test(1);
Test* t2 = t1; //t2 should be now a deep copy of t1
t1->value = 2;
cout << t1->value;
cout << t2->value;
Output is 22 but I expected '21'. What is the obvious thing I am missing here?
As Captain Obvlious suggests, call your assignment operator with
Test t2 = *t1
With this line
Test* t2 = t1
You are just making an assignment between pointers, so you are declaring a pointer to Test called t2 which will hold the same address held by the pointer t1.
When you modify the object using t1, you are actually changing the same object that also t2 is pointing to (this explains the output).
If you want to copy t1, you should use one of the following two ways:
Create a new Test object and copy construct it with t1:
Test t1;
Test t2(t1)
This code will call the copy constructor of the class Test:
Test::Test(const Test& t);
Use the assignment operator on an existing Test object:
Test t2;
t2 = t1;
As a general rule of thumb, when you need to define an operator=, then you probably need to define also a copy constructor and a destructor.
See the Rule of Three for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With