Monday 9 July 2018

destructor call explitly



using namespace std;
 
class Test
{
public:
    Test()  { cout << "Constructor is executed\n"; }
    ~Test() { cout << "Destructor is executed\n";  }
};
 
int main()
{
    Test();  // Explicit call to constructor
    Test t; // local object
    t.~Test(); // Explicit call to destructor
    return 0;
}
Output:
Constructor is executed
Destructor is executed
Constructor is executed
Destructor is executed
Destructor is executed 
When the constructor is called explicitly the compiler creates a nameless temporary object and it is immediately destroyed. That’s why 2nd line in the output is call to destructor.


we should never call destructor explicitly on local (automatic) object, because really bad results can be acquired by doing that.





























No comments:

Post a Comment