I was trying to learn basic C++ operator overloading concepts. I have a class mystring and related code as shown below. In functions used to overload ‘+’ operator, where can I free the memory to avoid memory leaks.
#include <iostream>
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 v1(str);
}
~mystring()
{
delete [] ptr;
}
};
int main()
{
mystring a="Hello",b="World",c;
c = a + b;
}
Simple fix:
Or have a private constructor
then