Assignment Operator

Let us understand assignment operator with the help of an example of employeeData class.

#include <iostream>
#include <string>
using namespace std;
class employeeData {
unsigned int m_salary;
char* m_name;
public:
~ employeeData() {
if (m_name) {
delete []m_name;
}
}
employeeData() {
cout << “employeeData default C’tor” << endl;
m_salary = 0;
m_name = NULL;
}
employeeData(unsigned int salary, char* name) {
cout << “employeeData parameterized C’tor” << endl;
m_salary = salary;
unsigned int len = strlen(name);
m_name = new char[len +1];
strncpy(m_name, name, len);
m_name[len+1] = ‘\0’;
}
//Overloaded Assignment Operator

employeeData& operator=(const employeeData& data) {
cout << “employeeData assignment operator” << endl;
if (this == &data) { //Self-reference check
return *this;
}
m_salary = data. m_salary;
char* temp = m_name;
unsigned int len = strlen(data.m_name);
m_name = new char[len + 1];
strncpy(m_name, data.m_name, len);
m_name[len+1] = ‘\0’;

delete []temp;
}
};
int main() {
employeeData e1(10000, “Vikas”);
employeeData e2(20000, “Alok”);
e1 = e2; //Assignment operator of employeeData is called.
return 0;
}

Assignment operator is called when an object is assigned to another object.

Important Points about Assignment Operator:

1) In C++, below operation is valid.
e1 = e1; //Assignment of same object

In the above operation, e1 is copied in to e1 again which is of no use. In order to avoid such scenario, self-reference check is added.

2) Assignment operator returns the current object by reference in order to support chaining operation.
E.g. a = b = c;
The above statement work like below:
a.operator(b.operator=(c))

For above statement to work, assignment operator must return the object (object on Left hand side) by reference.

That is why Assignment operator must return the current object i.e. object that calls assignment operator by reference.

3) Used in Deep copy operation. When a class contains pointer data member, then we need to define assignment operator otherwise it can lead to segmentation fault if one of the object goes out of the scope and other object tries to access pointer data member.

Related posts