0

When we call constructor explicitly then destructor also get called explicitly, so i tried deleting some dynamically allocated variable when destructor is called after putting it in a variable. But when i print that variable after destrucutor call it is still not deleted

#include<bits/stdc++.h>
using namespace std;

class Node{
   public:
   int *ptr;
   Node(){
        ptr = new int(5);
        cout<< ptr <<endl;
        cout<<"Constructor Called\n";
   }
   ~Node(){
        delete ptr;
        ptr = nullptr;
        cout<<"Destructor Called\n";
   }
};

int main(){
    int *ptrOfClass =  Node().ptr;
    cout<<"Hi\n";
    cout<< *ptrOfClass <<endl;
    return 0;
}

Output

0xf7bad0
Constructor Called
Destructor Called
Hi
5
  • 2
    Your pointer is deleted, you can see it here `Destructor Called`. Because your program uses a pointer after it has been deleted your program has *undefined behaviour*. Undefined behaviour means exactly what it says. It does not mean the your program has to fail, it does not mean that your program must print an error message. It just means that the behaviour of you program is undefined. In other words *anything could happen*, including what you saw happen. – john Aug 27 '22 at 08:17
  • 1
    Also worth reading: [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h?noredirect=1) and [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Yksisarvinen Aug 27 '22 at 08:17
  • "it is still not deleted" How did you come to that conclusion? What do you expect to happen when the object is in fact deleted? – n. m. could be an AI Aug 27 '22 at 08:22
  • Note that `ptr = nullptr;` in the destructor is pointless; the object is going away, and `ptr` doesn't exist any more. No conforming program can see its value (which is an extension of the issue in this question). – Pete Becker Aug 27 '22 at 12:43

0 Answers0