The following piece of code has a user defined data type called String
.Objects of this class store a char pointer str
(short hand for string) and length
.
#include<iostream>
#include<cstring>
using namespace std;
class String
{
char* str;
int length;
public:
String(){} //default constructor
String(const char* s)
{
length=strlen(s);
str=new char[length+1];
strcpy(str,s);
}
void add(String a,String b) //function to concatenate strings
{
length=a.length+b.length;
str=new char[length+1];
strcpy(str,a.str);
strcat(str,b.str);
}
void display()
{
cout<<str<<endl;
}
~String() //destructor
{
delete str;
cout<<"Destructor invoked!";
}
};
int main()
{
String s1;
String s2("Well done!");
String s3("Boy");
s1.add(s2,s3);
s1.display();
s2.display();
s3.display();
}
Output:
Destructor invoked!Destructor invoked!Well done!boy
X!!;
<!!;
Destructor invoked!Destructor invoked!Destructor invoked!
- It appears as though the destructor is invoked even before the
display
functions get invoked.Why is this?
If the destructor function were not defined, I get the following output(as expected):
Well done!boy
Well done!
boy
- Why is this unexpected output upon defining a destructor?