Not to use in any implementation but just for the sake of understanding I am trying to explicitly call a destructor using an object and another * to object.
CODE
#include<iostream>
using namespace std;
class A{
public :
A(){
cout<<"\nConstructor called ";
}
~A()
{
cout<<"\nDestructor called ";
}
};
int main()
{
A obj,*obj1;
obj1->~A();
obj.~A();
return 0;
}
OUTPUT

Now the problem is that I can't understand why destructor is called three times.
Even if the obj1 is not yet pointing to any object.
Note that I understand that the last two destructor calls are:
obj.~A();obj.I am using DevC++ 5.5.1
Your code only works by a fluke.
int main()
{
A obj,*obj1;
obj1->~A(); // (1) Bad reference that works
obj.~A(); // (2) Explicit call to destructor
return 0;
} // (3) obj's destructor is called when obj goes out of scope
obj1->~A();
You dereference the pointer obj1 which has not been initialized. That is undefined behaviour.
In this situation, anything can happen and nothing is guaranteed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With