Object still there after calling manual destructor for dynamically allocated object?

61 Views Asked by At

When two objects (one static and one dynamic) are created at same time then the destructor would delete them at same time (when object goes out of scope)?

Have a look at the below code block and its output:

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

// Destructor (NO return type & NO input parameter)
class Hero {
public:
    int health;
    
    Hero() { // constructor
        cout << "constructor is called" << endl;
    }

    
    ~Hero() {// destructor
        cout << "destructor is called" << endl;
    }
};

int main(){
    Hero h1; // static allocation (automatically call destructor)

    Hero *h2 = new Hero; // dynamic allocation (manually call destructor)
    delete h2;

    cout << "Size (static)  : " << sizeof(h1) << endl;
    cout << "Size (dynamic) : " << sizeof(h2) << endl;
    return 0;
}

Output:

enter image description here

I have following two doubts:

  1. Why Dynamic destructor is called first?
  2. Why even after calling the destructor the size of the dynamically allocated object is non-zero?

Basic thing about destructor that I know is, for dynamically allocated objects we need to manually call the destructor while for statically allocated objects it is called automatically.

1

There are 1 best solutions below

0
Alexander On

Why Dynamic destructor is called first?

Because you called it first.

h1's destructor doesn't run until its lifetime ends, which is at the end of the main function's body (at the }).

Why even after calling the destructor the size of the dynamically allocated object is non-zero?

You're checking the size of Hero*, which is always going to be the same, regardless of the value of the pointer (i.e. what it's pointing to).

This doesn't even have anything to do with destrcutors. See for yourself:

Hero *h = nullptr;
cout << "sizeof(nullptr) " << sizeof(h) << endl; // Non-zero, probably 4 or 8.