There are two reasons to use the initialization list:
Let's take a look at the first reason--necessity. (1) Initialization of another class member , (2) The member is a constant object, and (3) the member is a reference . Root cause: The compiler always ensures that all member objects are initialized before the constructor body executes (after the initialization of the list) .
The second reason to use the initialization list is for efficiency reasons when the member class has a default constructor and an assignment operator. Suppose you have a class CMyClass with a member of the CString type M_STR, and you want to initialize it to "Hi,how is you." You have two options:
Cmyclass::cmyclass () {cstring::operator= (LPCTSTR); m_str = _t ("Hi,how is You.");
Cstring::cstring (LPCTSTR) Cmyclass::cmyclass (): M_str (_t ("Hi,how is You.")) {}
What's the difference between them? Yes. The compiler always ensures that all member objects are initialized before the constructor body executes, so the code compiled in the first example calls Cstring::cstring to initialize the m_str, which is done before the control arrives at the assignment statement. In the second example, the compiler produces a call to CString:: CString (LPCTSTR) and "Hi,how is you." Passed to this function. The result is that two CString functions (constructors and assignment operators) are called in the first example, and only one function is called in the second example.
Under built-in types such as int or long or other types without constructors, there is no performance difference between the initialization list and the assignment of values in the constructor body. Either way, only one assignment will occur.
C + +: Initialize List