I have a somehow basic question regarding the conversion constructors and assignment operators. I can't find a similar question but maybe I am searching wrongly. Anyway.. I had made a class like this
class String
{
private:
// enum { SZ = 80 };
static const int SZ = 80;
char str[SZ]; //array
public:
String() //constructor, no args
{
cout << "Default constructor called, p_str = " << (void*)str << endl;
strcpy(str, "");
}
String( char s[] ) //constructor, one arg
{
cout << "Copy constructor called, p_str = " << (void*)str << endl;
strcpy(str, s);
}
void display() //display string
{
cout << str << endl;
// cout << "str ptr = " << (void*)str << endl;
}
void concat(String s2) //add arg string to
{ //this string
if( strlen(str)+strlen(s2.str) < SZ )
strcat(str, s2.str);
else
cout << "\nString too long";
}
void SetString(char* strToSet)
{
strcpy(str, strToSet);
}
// void operator =(const char* strCpy)
// {
// cout << "Copy assignemnt called..." << endl;
// strcpy(str, strCpy);
// }
~String()
{
cout << "Destructor called..." << endl;
}
void* GetStrPtr()
{
return (void*)str;
}
};
and in the main:
String myStr1 = "Hello Hello";
void* old_str_ptr = myStr1.GetStrPtr();
cout << "old_str_ptr = " <<old_str_ptr << endl;
myStr1 = "hello World!!";
cout << "old_str_ptr = " <<old_str_ptr << endl;
void* new_str_ptr = myStr1.GetStrPtr();
cout << "new_str_ptr = " <<new_str_ptr << endl;
myStr1.display();
cout << (char*)old_str_ptr << endl;
cout << (char*)new_str_ptr << endl;
This is the output I got:
Copy constructor called, p_str = 0x62fdd8
old_str_ptr = 0x62fdd8
Copy constructor called, p_str = 0x62fe28
Destructor called...
old_str_ptr = 0x62fdd8
new_str_ptr = 0x62fdd8
hello World!!
hello World!!
hello World!!
Destructor called...
Can someone explains what happens exactly at this line in main:
myStr1 = "hello World!!"
As I can see that it calls the conversion constructor (as the assignment operator is commented) and the address of "str" array is changed then what I don't understand is that the destructor is called and the address is returned back as seen in the output.