简体   繁体   中英

Question about class initialization in c++

I am learning c++ and I found something that puzzles me, and it's about the initialization of data members in a class.

Given this example:

class son
{
public:
    son(){
        std::cout << "constructing class son" << std::endl;
    }
};

class father
{
public:
    father(){
        std::cout << "constructing class father" << std::endl;
    }

private: 
    son s;
};

int main( int argc, char *argv[] ){
    father f; 
}

The output is:

constructing class son
constructing class father

I don't understant why the class son is initialized. It is supposed that the declaration in father is a declaration, and must be provided a proper initialization in the constructor of father() to initialize, but it appears that it is not needed in the case of class. Is that true?

Take a look at cppreference's description of constructors, especially the section on member initializer lists.

Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. Member initializer list is the place where non-default initialization of these objects can be specified.

Initialization order The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:

  1. If the constructor is for the most-derived class, virtual bases are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists)
  2. Then, direct bases are initialized in left-to-right order as they appear in this class's base-specifier list
  3. Then, non-static data member are initialized in order of declaration in the class definition.
  4. Finally, the body of the constructor is executed

In this case we're really only looking at lines 3 and 4 since there's no inheritance.

The key takeaway is that every member variable is initialized before the body of the constructor is entered, either default-initialized or according to the values in the member initializer list. Since father::father doesn't have one, it default-initializes s .

To create an object of the class father all its data members (sub-objects) must be created. So the object s (data member of the type son of the class father ) is created calling the default constructor of the class son .

After all sub-objects of the object of the class father have been created the body of the constructor father gets the control. That is the body of the constructor of the class father deals with already created data members of the object of the type father .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM