Stacks are Last in First Out(LIFO) data structures i.e item last inserted is the first one to be out. C++ perform function calls using stack data structure.The function Call Stack is used for function call/return mechanism as well as for creation,maintenance and destruction of each called function automatic variables. A Call Stack stores return address of calling function and also puts any function arguments on the stack.The main reason of using Call Stack is to return control to the point in calling function when called function finished it's execution.
When information about any subroutine is added to the Call Stack,it is termed as winding.Removing function information from the stack is Stack unwinding.Stack unwinding is also related to Exception handling.
Return from func3()
Return from func2()
Return from func1()
Main function is called
This program show normal flow of execution in functions.In main function func1() is called, from func1() func2() is called which in turn calls func3 therefore storing return addresses and information about calling function in Call Stack.When func3() terminates,entries from Call Stack are removed in LIFO manner as they finish execution. In this Destructor for each class object also shows LIFO behavior.
Stack Unwinding in Exception handling
Exception handling involves Stack Unwinding if an exception is not handled in the function in which it is thrown. In C++ when an exception occurs in a function, the Call Stack is linearly searched for exception handler, and all the subroutine before subroutine with exception handler are popped from function Call Stack.
Return from func3()
In this we have an exception in func3() as a result the exception is caught in catch block in main function.This time function terminate due to throw exception instead of normal return call.Still stack memory is freeing up but control does not stop at first return address instead stops at return address that resides in try block.Execution control passes to exception handlers at the end of try block rather than first statement in function call. Execution control does not stops at first return address but Destructor are still called for class object in reverse order.