Assignment Operator Overloading in C++

In C++, we can overload an operator for a user defined class to change its default behavior. C++ provides a default assignment operator, “=”, that provides member by member copy. This default behavior of the assignment operator does not always produce desired result.

The default assignment operator has the exact same problem that a default copy constructor has. Please have a look at the problem described in copy constructor article in detail.

In short, if a class has pointer type members, the default assignment operator will do a shallow copy in time of getting assigned from another other. Changing one object can have undesired impact on another.

#include <iostream>
#include <cstring>

using namespace std;

class mystring {
public:
    mystring(const char * s) {
        if (s == nullptr) {
            s = nullptr;
            return;
        }
        str = new char[strlen(s)];
        strcpy(str, s);
    }

    void change(const char * s) {
        if (s == nullptr || str == nullptr) return; /*Better handling possible. Not done for simplicity.*/

        strncpy(str, s, strlen(str));
    }

    friend ostream& operator<<(ostream& os, const mystring& s) {
        if (s.str == nullptr) return os;
        os << s.str;
        return os;
    }
private:
    char *str;
};

int main() {
    
    mystring s1("QnA Plus");
    mystring s2("");
    s2 = s1;
    
    cout << "First string: " << s1 << endl;
    cout << "Second string: " << s2 << endl;

    cout << "Chaning s1..." << endl;
    s1.change("XYZ");

    cout << endl;
    cout << "First string: " << s1 << endl;
    cout << "Second string: " << s2 << endl;

    return 0;
}
$ g++ -o test test.cpp 
srikanta@srikanta-vm:~/.../ss$ ./test 
First string: QnA Plus
Second string: QnA Plus
Chaning s1...

First string: XYZ
Second string: XYZ

In this program, we have two objects, s1 and s2 of type mystring. S2 gets assigned from s1. From the output, we can see that changing s1 changes the value of s2. Explanation in the copy constructor article.

Assignment Operator Overloading – the Solution

We can solve this problem by overloading the assignment operator for the mystring class.

#include <iostream>
#include <cstring>

using namespace std;

class mystring {
public:
    mystring(const char * s) {
        if (s == nullptr) {
            s = nullptr;
            return;
        }
        str = new char[strlen(s)];
        strcpy(str, s);
    }

    /*Overloaded Assignment Operator*/
    void operator= (const mystring &rhs) {
        if (str != nullptr) delete str;
        
        if (rhs.str == nullptr) {
            str = nullptr;
            return;
        }

        str = new char[strlen(rhs.str)];
        strcpy(str, rhs.str);
    }

    void change(const char * s) {
        if (s == nullptr || str == nullptr) return; /*Better handling possible. Not done for simplicity.*/

        strncpy(str, s, strlen(str));
    }

    friend ostream& operator<<(ostream& os, const mystring& s) {
        if (s.str == nullptr) return os;
        os << s.str;
        return os;
    }
private:
    char *str;
};

int main() {
    
    mystring s1("QnA Plus");
    mystring s2("");
    s2 = s1;
    
    cout << "First string: " << s1 << endl;
    cout << "Second string: " << s2 << endl;

    cout << "Chaning s1..." << endl;
    s1.change("XYZ");

    cout << endl;
    cout << "First string: " << s1 << endl;
    cout << "Second string: " << s2 << endl;

    return 0;
}
$ ./test 
First string: QnA Plus
Second string: QnA Plus
Chaning s1...

First string: XYZ
Second string: QnA Plus

After overloading the assignment operator, we can see that the output got changed. Now changing s1 does not impact s2. The overloaded assignment operator gets called one object is assigned from another, like, s2 = s1.

In the assignment operator overloaded function, we allocated memory for the target object to store its own value. And the value is copied from the source object to that allocated memory. So, after the assignment operation, both the objects will have their own memory spaces to hold their values. This type of copy is also referred as deep copy.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0