I learned that the destructor is called when an object goes out of scope and also the destructor deletes the objects. Ok fine, but what's happening here?
I'm calling the destructor explicitly, if it deletes the object then why is the destructor implicitly called? Even though there no object now because it's already deleted with the explicitly destructor calling. Sorry may be I'm wrong about explicitly and implicitly But try to understand my problem.
#include <iostream>
using namespace std;
class A{
public:
A(){
cout << "Constructor" << endl;
}
~A(){
cout << "Destructor" << endl;
}
};
int main(){
A obj;
obj.~A();
cout << "End" << endl;
}
Now
obj.~A();
The above line deletes the object. Then why again is the destructor called? Even though no object is there.
Output:
Constructor
Destructor
End
Destructor
An object which goes out of scope has its destructor called. That is an unchangeable guarantee which is mandated by the C++ language standard. It doesn't matter if you've manually called the destructor beforehand; when it goes out of scope, the destructor will be called. If you've written your destructor such that bad things happen if it's called twice, or if the extra behavior which the compiler inserts into the destructor code doesn't want to be called twice, bad things will happen.
This is one of many reasons why you should never manually call a destructor.