Hi Friends. I am Having some problems in running below program..
Please Help me..
The output I get is as follows..
Can anyone suggest other alternatives for that??
Thanks in Advance.....
Please Help me..
Code:
#include<iostream>
using namespace std;
class mystring
{
char* storage;
int size;
public: mystring() { storage=0;size=0; }
mystring(char* s)
{
size=strlen(s);
storage=new char[size+1];
strcpy(storage,s);
}
~mystring() { cout<<"Deleting"<<endl;delete [](storage); }
mystring operator + (mystring m)
{
char* temp=new char[size+m.size+1];
strcpy(temp,storage);
strcat(temp,m.storage);
mystring t(temp);
delete temp;
return t;
}
void display()
{
cout<<storage;
}
};
int main()
{
mystring a1("Hello ");
mystring a2("Anuj");
cout<<"a1=";a1.display();cout<<endl;
cout<<"a2=";a2.display();cout<<endl;
mystring a3;
a3=a1+a2;
cout<<"a1=";a1.display();cout<<endl;
cout<<"a2=";a2.display();cout<<endl;
cout<<"a3=";a3.display();cout<<endl;
}
I think the problem is the temp object(m), which deletes the original storage in "operator +" function ..(Please Tell me if I am wrong)anuj@edubuntu:05:55 PM:/media/ANUJ$ g++ -o mystring1.out mystring1.cpp
anuj@edubuntu:06:11 PM:/media/ANUJ$ ./mystring1.outa1=Hello
a2=Anuj
Deleting
Deleting
a1=Hello
a2=0�
a3= �o Anuj
Deleting
Deleting
Deleting
anuj@edubuntu:06:11 PM:/media/ANUJ$
Can anyone suggest other alternatives for that??
Thanks in Advance.....