Base class derived classes construct the sequence of destructor calls, member initialization, and destruction

Source: Internet
Author: User

# Include <iostream>
# Include <string>
# Include <cstdlib>
/*
Construction and initialization sequence:
1. initialize the class members of the base class
2. base class Constructor
3. class member initialization of a derived class
4. derived class Constructor

Destruction order:
1. Subclass destructor
2. Subclass class member analysis and destruction
3. destructor of the derived class
4. destructor and destruction of class members of a derived class

These two sequences can be understood through the inbound and outbound operations ~ The order is the opposite.
*/
Using namespace STD;
Class C
{
Public:
C () {cout <"Class C construct" <Endl ;}
~ C () {cout <"Class C destruct" <Endl ;}
};
Class base
{
Public:
Base () {cout <"base construct" <Endl ;}
~ Base () {cout <"Base destruct" <Endl ;}
C OBJ;
};
Class D
{
Public:
D () {cout <"Class D construct" <Endl ;}
~ D () {cout <"Class D destruct" <Endl ;}
};
Class child: public Base
{
Public:
Child () {cout <"Child construct" <Endl ;}
~ Child () {cout <"Child destruct" <Endl ;}
D obj1;
};

Int main ()
{
Child OBJ;
}
Execution result:

Class C construct
Base construct
Class D construct
Child construct
Child destruct
Class D destruct
Base destruct
Class C destruct

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.