Assignment Operator Between Two Structure Instances

◀ Flush the Output Buffer▶ Exceed Integer Limits
Amazon Some are confused about how a pointer is copied by using the assignment operator; so let’s discuss it. Let’s say you write a struct which contains an int and an int*. If you use the assignment operator ‘=’ between two instances of this struct, what will happen?

Run the following program:
#include <iostream>
using namespace std;

struct citizen {
int ssn;
int *age;
};

int main(int argc, char** argv){
citizen jerry,jesse; jerry.ssn = 0; jerry.age = new int; *jerry.age=20; jesse=jerry; cout << jerry.ssn << ' ' << *jerry.age << endl; cout << jesse.ssn << ' ' << *jesse.age << endl; jerry.ssn = 1; *jerry.age=21; jesse.ssn = 2; *jesse.age=22; cout << jerry.ssn << ' ' << *jerry.age << endl; cout << jesse.ssn << ' ' << *jesse.age << endl;
}
The output of running the program is as follows:

0 20
0 20
1 22
2 22

This simple program demonstrates an important point: when you use the assignment operator between two struct instances you perform assignment operator on each of the struct’s data members.
When you use the assignment operator between two objects, the left operand copies the contents of all data members of the right operand. Then they become two independent objects; changing the contents of one object has no effect on the other.


If, however, you use the assignment operator between two pointers, both of them point to the same address. Changing one’s value changes the other value as well.
Next let’s look at what happens when we exceed the integer limits!
◀ Flush the Output Buffer▶ Exceed Integer Limits

fShare
Questions? Let me know!