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;
~ 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;
return *this;

int main() {
char name1[] = "Vikas";
employeeData e1(10000, name1);
char name2[] = "Alok";
employeeData e2(20000, name2);
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:

  • 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.    To avoid such scenario, self-reference check is added.

  • 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:


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

  • 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.

  • Assignment operator can be overloaded as a member function and not as a friend function. The reason is that if it is not overloaded as a member function, precendence goes to default assignment operator provided by a compiler.

Related posts