Easy Tutorial
❮ Javascript Basic Reference Object Types Weui For Weixin Web ❯

C++ Class Constructor Initialization List

Category Programming Techniques

The constructor initialization list begins with a colon, followed by a comma-separated list of data members, each data member followed by an initialization expression in parentheses. For example:

class CExample {
public:
    int a;
    float b;
    // Constructor initialization list
    CExample(): a(0), b(8.8)
    {}
    // Constructor internal assignment
    CExample()
    {
        a = 0;
        b = 8.8;
    }
};

In the example above, the results of the two constructors are the same. The top constructor (the one using the initialization list) explicitly initializes the class members; the constructor without the initialization list assigns values to the class members without explicit initialization.

There is not much difference between initialization and assignment for built-in type members, and either of the above constructors can be used. For non-built-in type member variables, to avoid double construction, it is recommended to use the class constructor initialization list. However, sometimes it is necessary to use a constructor with an initialization list:

What is the meaning of initializing data members and assigning to data members? What is the difference?

First, categorize the data members by type and explain the situation:

Points to note:

Member initialization order in the initialization list:

When C++ initializes class members, it is done in the order they are declared, not the order they appear in the initialization list.

class CMyClass {
    CMyClass(int x, int y);
    int m_x;
    int m_y;
};

CMyClass::CMyClass(int x, int y) : m_y(y), m_x(m_y)
{
};

You might think that the above code will first do m_y=I, then do m_x=m_y, and finally they will have the same value. However, the compiler first initializes m_x, then m_y, because they are declared in this order. The result is that m_x will have an unpredictable value. There are two ways to avoid it, one is to always declare members in the order you want them to be initialized, and the second is, if you decide to use an initialization list, always list these members in the order they are declared. This will help eliminate confusion.

>

Original article: http://www.cnblogs.com/BlueTzar/articles/1223169.html

❮ Javascript Basic Reference Object Types Weui For Weixin Web ❯