Working of assignment operator while copying objects

Viewed 532

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;
}
5 Answers

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 use a pointer in your class since two object the origin and assigned object access to same memory address so if you change this memory location the modification is visible for two objects.

#include<bits/stdc++.h>
using namespace std;
class A
{
   public:
     int x;
     int *y;
};

int main()
{
 A a1,a2;
 a1.x=5;
 a1.y = new int(7);
 a2.x=5;
 a2=a1;
 a1.x=10;
 *a2.y = 9;
 cout<<a1.x<<" "<<a2.x;
 cout<<*a1.y<<" "<<*a2.y; // the output is 9 9/ because both object access two same memory address
 return 0;
}

The values of a1 are copied in a2. If your class had pointer, then the pointer value, ie the address would be copied the same, which would mean that had be sharing same address and then changing value in one is changing value in the other as well.

When the bitwise assignment is performed both the object shares the same memory location and changes in one object reflect in another object.

is wrong. Copying is copying. This means data in the memory location for source object is copied to another memory location for destination object. No memory location sharing is done.

You understanding of default assignment operators is incorrect, default assignment operators use a copying method known as a member-wise copy. I will not share the memory.

Since, you misunderstood the concept, there is an expected behavior.

Related