Can somebody explain here how destructor is called for object created in heap via new operator when the corresponding delete is not called. In addition since in below code we are catching object via const reference and in destructor we are changing object value (i.e. setting n=0), so how is that possible.
class A
{
private:
int n;
public:
A()
{
n=100;
std::cout<<"In constructor..."<<std::endl;
}
~A()
{
n=0;
std::cout<<"In destructor..."<<std::endl;
}
};
int main()
{
try
{
throw *(new A());
}
catch(const A& obj)
{
std::cout<<"Caught...."<<std::endl;
}
return 0;
}
Output from program (running on http://cpp.sh/3jm4x):
In constructor... Caught.... In destructor...
staticcounter that you increase in the constructor and check in the destructor. - Some programmer dude