Reputation: 315
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;
}
Upvotes: 0
Views: 96
Reputation: 2089
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);
Upvotes: 1
Reputation: 76523
The assignment operator takes its argument by value; the copy constructor is used to set up that argument.
Upvotes: 2