The assignment operator copies one object to another member-wise. If you do not overload the assignment operator, it performs the bitwise copy. When the bitwise assignment is performed both the object shares the same memory location and changes in one object reflect in another object. This concept and my code goes contrary. Can someone please explain me why..
#include<bits/stdc++.h>
using namespace std;
class A
{
public:
int x;
};
int main()
{
A a1,a2;
a1.x=5;
a2.x=5;
a2=a1;
a1.x=10;
cout<<a1.x<<" "<<a2.x;
return 0;
}
When the bitwise assignment is performed both the object shares the same memory location and changes in one object reflect in another object.
This is incorrect. Bitwise copy assignment does not lead to objects sharing the same memory. It's a separate copy, so a2 and a1 are in fact in different memory location.
This concept and my code goes contrary.
You probably got mixed up with the case where copy assignment is done with a pointer member variable. In that case, indeed the default bitwise assignment would lead to objects having pointers pointing to the same memory, and requires deep copy assignment instead (of the default assignment).
Your current code does not have any pointer member though, so such deep copy is not required.
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