Demo demoObjA;
demoObjA.~Demo();
You're doing it wrong.
demoObjA
is an automatic variable. You do not manually destroy an automatic variable like this. Automatic variables will be automatically destroyed when they fall out of scope.
The code you have written to call the destructor is legal in C++, but highly unusual. You would never directly call a destructor unless you knew exactly what you were doing and why, and never for automatic variables (at least not any case I can think of). [Note: the only time you would normally directly call a destructor is on an object that has been instantiated using placement-new -- itself a highly unusual operation.]
Also,
demoObjA.~Demo();
cout << demoObjA.a << endl;
You seem to be asking why demoObjA.a
still has a value of 1
(or any value at all) after you have called the destructor. The problem is, you have entered in to the land of Undefined Behavior. Once you call the destructor for demoObjA
, the object is destroyed. You can't then access the members of demoObjA
. If you do, it results in Undefined Behavior. Undefined Behavior means "anything can happen" and that includes reading a value that you previously stored in the object. It might look like your code is working, but it's not.