when is the destructor fire?
if the object is created on the stack, the destructor is called automatically when the object is out of its scope. if the object is created on the heap using new operator, the destructor is fired explicity by using delete keyword.
i created an example to demonstrate both cases:
#include <iostream>
#include <string>
using namespace std;
class deneme
{
public:
deneme();
~deneme();
};
deneme::deneme()
{
cout<< "constructor fired" << endl;
}
deneme::~deneme()
{
cout << "destructor fired" << endl;
}
void CreateInstance()
{
deneme mydeneme;
}
void CreateInstanceUsingNew()
{
deneme * mydeneme = new deneme();
delete mydeneme;
}
int main()
{
CreateInstance();
CreateInstanceUsingNew();
return 0;
}
when you run the code the output is as follows:
constructor fired
destructor fired
constructor fired
destructor fired
serkan sendur
Postaholic
2,062 posts since Jan 2008
Reputation Points: 854
Solved Threads: 127