Problems with explicit constructor calls

45 Views Asked by At

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
0

There are 0 best solutions below