0
class A{ public: int x=2; ~A(){x++;} }; int main() { A ob; cout<<ob.x; } Why does it print 2? And why does it print 3 when you remove the ~ and turn it into a constructor?
5 Réponses
+ 2
It prints 2 because you are printing x before the destructor even runs. In this case, you aren't deleting the object at any point so the destructor is going to run at the end of the program, where the object is automatically destroyed.
When you have it as a constructor, it prints 3 because when you create the object, the constructor runs, incrementing x. THEN you print out x, which is 3.
+ 1
delete ob;
Deletes an object if you ever feel the need to call a destructor early. For smaller programs like this, destructors are usually made for clearing up, so you could always wait until the end of the program where the object is automatically destroyed, rather than deleting it.
+ 1
Because like I said, the a destructor only executes once an object has been destroyed, be it through the delete keyword, or end-of-program. Therefore, the x++ for the destructor will initiate after you print out x, so technically x is 4 at the end of the program, you just aren't printing it out then.
0
Then I still don't get how to delete
0
Then why isn't the destructor automatically called when I include the both constructor and destructor in this program? It continues to only print 3