Saturday, 2 July 2016

When destructor of the local objects will be called when go to is used within the function block?

 
Guess the output?

#include<iostream>

class ArrayNotFound
{
private:
       int m_id;
      
public:
       ArrayNotFound(int id)
       {
             std::cout<<"ArrayNotFound constructor called for ID: "<<id<<std::endl;
             m_id=id;
       }
      
       ~ArrayNotFound()
       {
             std::cout<<"ArrayNotFound destructor called for ID: "<<m_id<<std::endl;
       }
};

int main()
{
int c=1;
ArrayNotFound obj(1);
MyLabel:
ArrayNotFound obj2(2);
if(c == 1)
{
       c=0;
       goto MyLabel;
}
      
return 0;
}

Answer:


ArrayNotFound constructor called for ID: 1
ArrayNotFound constructor called for ID: 2
ArrayNotFound destructor called for ID: 2
ArrayNotFound constructor called for ID: 2
ArrayNotFound destructor called for ID: 2
ArrayNotFound destructor called for ID: 1

Explanation:


Whenever label is used in the program, and if control of the program is returned due to goto statements then destructor will be called for the objects declared under the label.  
Since obj2 is declared under the MyLabel destructor is called for that object. One should notice that destructor is not called for obj because it is above the label statement. But destructor for obj will be called once at the end of the main function block

Consider the following statement,


MyLabel:
ArrayNotFound obj2(2);
if(c == 1)
{
       c=0;
       goto MyLabel; // Desctructor will be called for obj2
}