Destructor problem in C++

Status
Not open for further replies.

anuj919

Broken In
Hi Friends. I am Having some problems in running below program..
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;
}
The output I get is as follows..
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$
I think the problem is the temp object(m), which deletes the original storage in "operator +" function ..(Please Tell me if I am wrong)
Can anyone suggest other alternatives for that??
Thanks in Advance.....
 

lilovirus

Broken In
Hi,
in operator overloading function you are returning a local variable, which will be out of scope when this function returns. put that variable on heap and you will get the desire result.

if you are passing an object to some function make sure you pass it by reference.
else while doing inheritance it will create a problem.

if you are not changing argument inside the function pass as const reference.

I hope you understand.
 
Last edited:
Status
Not open for further replies.
Top Bottom