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:
I have following two doubts:
- Why Dynamic destructor is called first?
- 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.

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}).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: