cplusplus initialization sequence

1. The order of inheritance;

#include<iostream>

using namespace std;

class  AAA
{
    public:
    AAA(){
        cout<<"AAA"<<endl;
    }
};

class BBB
{
    public:
    BBB(){
        cout<<"BBB"<<endl;
    }
};

class CCC: public BBB , AAA
{
    public:
    CCC(){
        cout<<"cccc"<<endl;
    }
};


int main()
{
    CCC c1;

    return 0 ;

}

Output result:

./a.out
BBB
AAA
cccc 

 

2. The order of declaration:

#include<iostream>

using namespace std;

class  AAA
{
    public:
    AAA(){
        cout<<"AAA"<<endl;
    }
};

class BBB
{
    public:
    BBB(){
        cout<<"BBB"<<endl;
    }
};

class CCC
{
    public:
    CCC():a1(),b1(){
        cout<<"cccc"<<endl;
    }

    BBB b1;
    AAA a1;
    
};


int main()
{
    CCC c1;

    return 0 ;

}

Output result:

./a.out
BBB
AAA
cccc

3. The role of the initialization list:

  • Constant members, because constants can only be initialized and cannot be assigned, they must be placed in the initialization list.

  • For reference types, references must be initialized when they are defined and cannot be reassigned, so they must also be written in the initialization list.

  • There is no default constructor for the class type, because the initialization list can be initialized without calling the "default constructor + copy assignment operator", but directly by calling the "copy constructor" for initialization.

 

 

reference:

https://www.cnblogs.com/silenzio/p/11766609.html

Guess you like

Origin blog.csdn.net/zgb40302/article/details/115365828