C ++ initialization list (1)

Source: Internet
Author: User

C ++ initialization list (1)
What is the initialization list?

Unlike other functions, constructor can have an initialization list in addition to the name, parameter list, and function body. The initialization list starts with a colon, followed by a series of initialization fields separated by commas. In C ++, the only difference between struct and class is that all the members of struct are public by default. Therefore, if the accessibility of members is not considered, there is no difference between them, here we do not consider the issue of access, so the following code uses struct for demonstration.

Struct foo {string name; int id; foo (string s, int I): name (s), id (I) {}; // initialization list };
Two execution phases of the constructor

The execution of constructor can be divided into two phases: initialization and Computing. The initialization phase is prior to the computing phase.

Initialization phase

All class type members are initialized during the initialization phase, even if the member does not appear in the initialization list of the constructor.

Computing stage

It is generally used to perform the assignment operation in the constructor body. The following code defines two structs. Test1 has constructor, copy constructor, and assign value operator, In order to conveniently view the results. Test2 is a test class. It takes the Test1 object as a member. Let's take a look at how the constructors of Test2 are executed.

 
Struct Test1 {Test1 () // No parameter constructor {cout <Construct Test1 <endl;} Test1 (const Test1 & t1) // Copy the constructor {cout <Copy constructor for Test1 <endl; this-> a = t1.a;} Test1 & operator = (const Test1 & t1) // value assignment operator {cout <assignment for Test1 <endl; this-> a = t1.a; return * this ;}int a ;}; struct Test2 {Test1 test1; test2 (Test1 & t1) {test1 = t1 ;}};
 

Call Code

Test1 t1 ;Test2 t2(t1) ;

Output

To explain, the first line of output results corresponds to the first line in the call code to construct a Test1 object. The second line of output corresponds to the Code in the Test2 constructor. The default constructor is used to initialize the object test1, which is called the initialization phase. The third row outputs the value assignment operator corresponding to Test1 and assigns values to test1. this is the so-called computing stage.

Why use the initialization list?

There are two ways to initialize a class member: one is to use the initialization list, and the other is to assign values in the constructor body. The use of the initialization list is mainly based on performance issues. For built-in types such as int and float, the use of initialization class tables is not very different from the initialization in the constructor body, but for class types, it is best to use the initialization list. Why? From the test above, we can see that the process of calling the default constructor is missing from the initialization list, which is very efficient for data-intensive classes. Let's take a look at the example above. We use the initialization list to implement the Test2 constructor.

struct Test2{    Test1 test1 ;    Test2(Test1 &t1):test1(t1){}}

Use the same call code. The output result is as follows.

The first line outputs the first line of the corresponding call code. The second line outputs the initialization list corresponding to Test2 and directly calls the copy constructor to initialize test1, saving the process of calling the default constructor. Therefore, we recommend that you use the initialization list whenever possible when using the initialization list.

What must be included in the initialization list

In addition to performance problems, in some cases, the initialization list is indispensable. In the following situations, you must use the initialization list.

  • Constant members. Because constants can only be initialized and cannot be assigned values, they must be placed in the initialization list.
  • The reference type. The reference must be initialized during definition and cannot be re-assigned. Therefore, it must also be written in the initialization list.
  • There is no default constructor class type, because you do not have to call the default constructor to initialize the object using the initialization list, but directly call the copy constructor to initialize the object.

    For classes without default constructor, let's look at an example.

     
    struct Test1{    Test1(int a):i(a){}    int i ;};struct Test2{    Test1 test1 ;    Test2(Test1 &t1)    {        test1 = t1 ;    }};
     

    The above Code cannot be compiled because the test1 = t1 line in the Test2 constructor is actually executed in two steps.

    1. Call the default constructor of Test1 to initialize test1.

    2. Call the value assignment operator of Test1 to assign a value to test1.

    However, because Test1 does not have a default constructor, the so-called first step cannot be executed, so the compilation is incorrect. The correct code is as follows. Use the initialization list instead of the value assignment operation.

    struct Test2{    Test1 test1 ;    Test2(Test1 &t1):test1(t1){}}
    Initialization sequence of member variables

    Members are initialized in the order they appear in the class, rather than in the order they appear in the initialization list. Read the code.

    Struct foo {int I; int j; foo (int x): I (x), j (I) {}; // OK, initialize I first, and then initialize j };

    Let's look at the following code.

    Struct foo {int I; int j; foo (int x): j (x), I (j) {}// I value undefined };

    Here, the I value is undefined. Although j appears in the initialization list before I, I is prior to j, So I is initialized first, But I is initialized by j, at this time, j has not been initialized, so the I value is undefined. Therefore, a good habit is to initialize according to the sequence defined by members.

    Let's take a look at the following code.

    Class Data {

    Public:
    Int I;
    Int j;
    Int k;
    Data (int a): j (a), k (I), I (I)
    {
    }
    };
    There is a problem with this writing method. According to this writing method, only the value of j is equal to the value of a, and the values of k and I are undefined.

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.