1 #include<iostream> 2 using namespace std; 3 4 class Human{ 5 public: 6 Human(){ 7 cout<<"constrct"<<endl; 8 } 9 ~Human(){10 cout<<"destruct"<<endl;11 }12 private:13 int age;14 };15 16 int main(){17 Human human;18 19 Human *humanPtr;20 humanPtr = new Human();21 delete humanPtr;22 23 system("pause");24 return 0;25 }
What is the output of the above Code? As follows:
Constrctconstrctdestruct press any key to continue...
Why does Mao have only one destruct? Is the first object not destructed? No! When the main function executes return, the Destructor will be called.
Do not believe it. Check the following code:
1 #include<iostream> 2 using namespace std; 3 4 class Human{ 5 public: 6 Human(){ 7 cout<<"constrct"<<endl; 8 } 9 ~Human(){10 cout<<"destruct"<<endl;11 }12 private:13 int age;14 };15 16 int test(){17 Human human;18 return 0;19 }20 21 int main(){22 23 test();24 25 Human *humanPtr;26 humanPtr = new Human();27 delete humanPtr;28 29 system("pause");30 return 0;31 }
The output is as follows:
Constrctdestructconstrctdestruct press any key to continue...
Now, after test () is called, The Destructor is called.