I am trying to learn C ++ and am writing programs to study constructor overloading and overloading. I am surprised that the program below does not crash when using the Copy constructor, saying "Double Free", whereas when using Operator = overloading sequences it crashes sequentially.
#include <iostream>
using namespace std;
class XHandler
{
public:
XHandler()
{
data = new char[8];
strcpy(data, "NoName");
}
XHandler (const char *str)
{
data = new char (strlen(str) + 1 );
strcpy (data, str);
}
XHandler (const XHandler &xh)
{
data = xh.data;
}
XHandler& operator = (const XHandler &xh)
{
data = xh.data;
}
~XHandler()
{
delete data;
}
void debug()
{
cout << data <<endl;
}
private:
char *data;
};
int main()
{
XHandler wm("hello"), wb("there");
wm.debug();
wb.debug();
XHandler wc (wm);
wc.debug();
XHandler wd;
wd = wc;
wd.debug();
}
, , , "" . "wd" "wc", . , . , wc wm , .
XHandler wd;
wd = wc;
wd.debug();
, - undefined. , .