Let consider the code in main step by step. Let start from the following statement
MyString str3 = str1 + str2 ;
It could be rewriten as
MyString str3 = str1.operator + ( str2 ) ;
Let look the definition of the operator +
1 2 3 4 5 6 7
|
MyString operator + (MyString obj){
MyString tempString ;
tempString.name = new char[strlen(obj.getName()) + strlen(name) + 1];
strcpy(tempString.name,name); //copy the first string
strcat(tempString.name,obj.getName()); //concatenate with the second string
return tempString ;
}
|
It has a parameter of type MyString that accepts an argument by value. So a copy constructor has to be called to create local variable (parameter) obj from argument str2. Because you did not define the copy constructor then implicitly defined by the compiler copy constructor will be called. All what it does is assigning str.name to obj.name.
So there are two objects, str and obj, members of which with name 'name' point to the same string.
After exiting this operator object obj will be destroyed. It means that memory pointed to by both name(s) will be freed. The destructor for object obj issues the message
Now the state of object str2 is undefined because its member name points to unallocated memory.
Inside the operator there is another local object with name tempString. It also shall be deleted but due to the compiler optimization it simply becomes str3. That is the compiler does not call the copy constructor and corresponding destructor.
This output
corresponds to the statement
cout << str3 << "\n"; //does not give any error
Then the following statement is executed
1 2
|
if(str1 <= str2 ){
cout <<"String 1 contains less than or equal characters than String 1" << endl;
|
that is operator
1 2 3 4 5 6 7
|
bool operator <= (MyString obj){
if(strlen(name) <= strlen(obj.getName())){
return true ;
}else {
return false ;
}
}
|
is called. It again has a parameter that accpets an argument by value. This means that a local object that is a copy of str2 will be created and after exiting the operator will be deleted.
Here the corresponding destructor message for this local object
Now you have three objects str3, str2 and str1. str2 has undefined state because its member name points to already freed memory. The objects are deleted in the reverse order relative to their creations. So the first will be deleted str3, then str2, and at last str1.
So the last three messages correspond to three call of the destructor
Deallocating memory RamanGhai
Deallocating memory è3/
Deallocating memory Raman
|