This is a naive example I have coded to study C++ operator overloading. When I execute it, code hangs at the statement c = a + b; and control never reaches c.display();
As part of debugging if I put a cout << ptr << '\n'; in the assignment operator overloaded function it does print out HelloWorld, so string doesn’t seem to be malformed.
Why does it hang then? What am I missing ??
class mystring
{
char *ptr;
public:
mystring(char *str = "")
{
ptr = new char[strlen(str) + 1];
strcpy(ptr,str);
}
mystring operator +(mystring s)
{
char *str = new char[strlen(ptr) + strlen(s.ptr) + 1];//where should this memory be freed
strcpy(str,ptr);
strcat(str,s.ptr);
return mystring(str);
}
void operator =(mystring s)
{
strcpy(ptr,s.ptr);
//cout << ptr << '\n'; \\Debug - this prints out HelloWorld but still hangs
}
void display()
{
cout << ptr << '\n';
}
~mystring()
{
delete [] ptr;
}
};
int main()
{
mystring a="Hello",b="World",c;
c = a + b;
c.display();
getchar();
}
EDIT: Compiler: MS-Visual C++ 2010 Express / Windows.
I think that what you are getting is a memory error. This line:
does the following:
and your operator= fails to allocate memory
What you need is: