top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

c++: Is it possible to call constructor and destructor explicitly?

+2 votes
525 views
c++: Is it possible to call constructor and destructor explicitly?
posted Nov 2, 2014 by Upma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Yes, it is possible to call special member functions explicitly by programmer. Following program calls constructor and destructor explicitly.

#include <iostream>
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.

answer Nov 5, 2014 by Amit Kumar Pandey
...