Wednesday 22 February 2012

What happens if a local variable is destroyed within its scope before a program is completely executed? Can a destructor be called if needed? | Constructor in C++

No, the destructor cannot be called if needed. Let's understand the preceding statement with the help of an example. There is a local variable n of a class Notebook. Now, the destruction of the local variable n occurs before the execution of a program:
Class Notebook
{
int n;
void bcd()
Notebook n;
// ..Insert code that should execute when n is still in it's scope..
we want the side-effect of n's destructor here!
// ..Insert code that should execute after n is destroyed..
}
On calling a destructor explicitly, an undefined behavior is occurred, because the destructor may invoke twice for the local variable. Firstly, on explicit calling and secondly automatic calling when the local variable destroys. Therefore, a destructor cannot be called explicitly if needed.