Hi I have created a small program which just adds two char* with the help of overloaded + operator, but getting problem with destructor.
#include<iostream>
#include<string.h>
using namespace std;
class base
{
private:
char* name;
public:
base();
~base();
void display(void);
base(const char*);
base(const base&);
base operator+(base foo);
};
base::base()
{
cout<<"base initialized"<<endl;
}
base::~base()
{
cout<<name<<"destructor called"<<endl;
delete name;
}
void base::display()
{
cout<<"Name is: "<<name<<endl;
}
base::base(const base& foo)
{
cout<<"copy called\n" ;
name = new char(strlen(foo.name)+1);
strcpy(name, foo.name);
}
base::base(const char* foo)
{
name = new char(strlen(foo)+1);
strcpy(name, foo);
}
base base::operator+(base foo)
{
base temp;
temp.name = new char(strlen(name)+strlen(foo.name)+1);
strcpy(temp.name,name);
strcat(temp.name,foo.name);
return temp;
}
int
main(int argc, char** argv)
{
base b1 = "alex";
base b2 = "parera";
base t1,t2,t3;
t1 = b1;
t2 = b2 ;
t3 = b1+b2;
b1.display();
b2.display();
t1.display();
t2.display();
t3.display();
return 0;
}
Here when program execution comes at t3 = b1+b2 point , it calls destructor and I am getting error, I can not see the concatenated string.. ie alexparera.
following is the output of the program
base initialized
base initialized
base initialized
copy called
base initialized
alexpareradestructor called
pareradestructor called
Name is: alex
Name is: parera
Name is: alex
Name is: parera
Name is:
destructor called
pareradestructor called
alexdestructor called
0�radestructor called
�destructor called
So My question is when I have not finished using t3 object in my program, y it calls the destructor and swaps out memory ??