The order in which constructors and destructors of a class are called

Source: Internet
Author: User

First, a snippet of code:

1#include <iostream>2 using namespacestd;3 4 classclock{5 Private:6     inth,m,s;7  Public:8Clock (intH=0,intm=0,ints=0){9h=h,m=m,s=s;Tencout<<"Constructor:"<<H<<":"<<M<<":"<<S<<Endl; One     } A~Clock () { -cout<<"destructor:"<<H<<":"<<M<<":"<<S<<Endl; -     } the }; -  - intMain () { -Clock C3 (Ten,0,0); +Clock C4 ( One); -     return 0; + } AClock C1 (8); atClock C2 (9);

The result is:

We can find several points:

1. Set up the global object first, then set up the local object. Same as normal variable establishment order.

2. Destructors are called in reverse order, because local objects are established in the stack.

3. The destruction of the global object is not displayed, it is called at the end of the program and is not displayed naturally.

The order in which constructors and destructors of a class are 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.