简体   繁体   中英

How can the synthesized default constructor initialize already initialized class members?

I am learning about classes, and chapter 7.1.4 of the book C++ Primer says the following:

The compiler-generated constructor is known as the synthesized default constructor . For most classes, this synthesized constructor initializes each data member of the class as follows:

  • If there is an in-class initializer (§ 2.6.1, p. 73), use it to initialize the member.
  • Otherwise, default-initialize (§ 2.2.1, p. 43) the member.

If the class members already have an in-class initializer, why would this synthesized default constructor initialize them again? Also, I thought that initialization is a thing that can only happen once. The above suggest that the members are initialized twice, once explicitly, and once implicitly by the synthesized default constructor.

In class initializers don't actually initialize anything. All they are are syntactic sugar for use this initializer if none is provided. So, with

struct foo
{
    int a = 42;
    int b;
};

The compiler is going to generate a constructor like

foo() : a(42)/*, b()*/ {}

Since a has an "initializer" and b does not. note the b() is just exposition. since b is an int no initialization happens to it.

In a more complicated constructor like

struct foo
{
    int a = 42;
    int b;
    foo() : b(21) {}
};

Since the a member is missing from the class member initialization list, the compiler will add a(42) to the list because that is the default initializer to use.

If you had

struct foo
{
    int a = 42;
    int b;
    foo() : a(3), b(21) {}
};

Then the default initializer is ignored and a will have the value of 3 instead of 42 .

There is nothing there about initializing the member again . If there is an in-class initializer, the synthesized default constructor uses it and that is the first initialization of that member. Members are not initialized before the constructor is called, even if they have in-class initializer.

You can understand in-class initializer as a instruction for the compiler, how to build the constructor in case no other initialization was provided for it.

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