0

Can anybody explain me, why in my below code, where ms3 = ms1 is done, both copy and assignment operator get called in this line. In the above mentioned line only overloaded assignment operator should get called as per my knowledge. But both the copy constructor and assignment operator are getting called. Please explain me.. why this happens?

class MyString {
private:
    char* string;
public:
    MyString(char *ptr = NULL);
    MyString(MyString &str);
    MyString &  operator =(MyString  str);
    ~MyString();
};

MyString::MyString(MyString &str) {
    printf("Copy Constructor called !!!\n");
    int len = strlen(str.string);
    string = new char[len+1];
    strcpy_s(string, len+1, str.string);
}

MyString::MyString(char* str) {
    printf("Constructor called !!!\n");
    if (str != NULL) {
        int len = strlen(str);
        string = new char[len + 1];
        strcpy_s(string, len + 1, str);
    }
    else {
        string = NULL;
    }

}
MyString & MyString::operator=(MyString str) {
    printf("Assignment Operator!!!\n");
    if (&str == this) {
        return *this;
    }

    delete[] string;
    if (&str != NULL) {
        int len = strlen(str.string);
        string = new char[len + 1];
        strcpy_s(string, len+1, str.string);
    }
    return *this;
}
MyString::~MyString() {
    printf("Destructor\n");
    delete[] string;
}

int _tmain(int argc, _TCHAR* argv[])
{
    MyString ms = "ABC";
    MyString ms1("EFG");
    MyString ms2 = ms1;
    MyString ms3;
    ms3 = ms1;
    MyString ms4 = ms3 = ms1;
    return 0;
}
mojo1mojo2
  • 1,062
  • 1
  • 18
  • 28
San
  • 315
  • 1
  • 3
  • 12
  • `if (&str == this)` is always false because `str` is a local variable. Also `if (&str != NULL)` is always true because the address of a local variable can't be 0. – Emil Laine May 08 '16 at 01:56

2 Answers2

2

The assignment operator takes its argument by value; the copy constructor is used to set up that argument.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • A detailed explanation is found here (http://stackoverflow.com/questions/5368258/the-copy-constructor-and-assignment-operator) to answer "why"? – NonCreature0714 May 08 '16 at 01:44
1

To avoid this, your need to rewrite your assignment operator so that it takes a reference, like the copy constructor does. Also you should use const :

MyString(MyString const &str);
MyString & operator=(MyString const &str);
Johan Boulé
  • 1,936
  • 15
  • 19