[C ++ Basics] 008 _ class constructor and destructor

Source: Internet
Author: User
 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.