C++ : Overload Assignment (=) operator

Just like a copy constructor the compiler provides a default free implementation of the assignment operator for a class. The compiler provided assignment operator implementation does a member-wise copy of the data members. This is often referred to as shallow copying.

Overload ‘=’ (assignment) operator
// Inside main ( )
ย ย ย ย ย  String obj_1 (“EARTH”);
ย ย ย ย ย  String obj_2 (“BLUE”); ย ย ย 
ย ย ย ย ย  obj_1 = obj_2; ย ย ย ย ย ย ย ย ย ย ย ย // Resolved as => obj_1 . operator = ( obj_2 )
ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย // This statement leads to the member wise copy that leads to the dangling pointer and memory leakage problem.

The shallow copying of the data members give rise to the below problems

  • Dangling pointer
  • Memory leakage : With the compiler provided assignment operator implementation, the address in the pointer data member of the source object ( obj_2 ) gets copied in the pointer data member of the destination object ( obj_1 ). It is quite clear that the address existing in the previous destination object has now been overwritten. Thus the address of the memory that it had been pointing is lost and there is no way of freeing it.

C++ program for a String class demonstrates the overloading of assignment operator.


class String {

    u_int m_len;
    char* m_buff;


    // Default constructor
    String () {
       m_len = 0;
       m_buff = new char;
       m_buff[0] = '\0';

    // Parameterized constructor
    String (const char * str) {
       m_len = strlen(str);
       m_buff = new char[m_len + 1];
       strcpy(m_buff, str);

    // Overloading of = / assignment operator for String class.
    // Overload is needed to avoid dangling pointer that would cause errors.
    String& operator = (const String& obj) {
        if (this != &obj) { // If the source obj is same as the destn object, no need to copy.
            m_len = obj.m_len;
            delete [] m_buff; // Delete the old buffer of the destination object.
            m_buff = new char[m_len+1];
            strcpy(m_buff, obj.m_buff);
            return (*this);
        return (*this);

    ~String() {
       std :: cout << "Destructor got called." << std :: endl;
       if (m_buff) {
           delete [] m_buff;

    void Display() {
        std :: cout << m_buff << std :: endl;

int main() {

   String s1("Take_It_Easy");
   String s2("Hurray");

   std :: cout << "String s1 : ";

   std :: cout << "String s2 : ";

   s1 = s2;
   std :: cout << "After assignment, String s1 : " ;

   std :: cout << "Main ends. Now returning" << std :: endl;
   return 0;


String s1 : Take_It_Easy
String s2 : Hurray
After assignment String s1 : Hurray
Main ends. Now returning
Destructor got called.
Destructor got called.

Copyright (c) 2019-2022, Algotree.org.
All rights reserved.