Initialization list in C ++

Source: Internet
Author: User
Tags c constructor

1. Initialization list:

Unlike other functions, constructor not only has names, parameter lists, and function bodies, but also has an initialization list. The initialization list starts with a colon followed by a series of initialization fields separated by commas.
struct foo { 
     string name ; 
     int id ; 
Foo (string S, int I): name (s), ID (I) {}; // initialization list
};
2. 

The execution of constructor can be divided into two phases: initialization and Computing. The initialization phase is prior to the computing 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.
3. When to use the initialization list: the C ++ language specifies that the initial values of data members cannot be directly specified in the class body. Therefore, the initialization function of an object is completed by calling the object constructor. The initialization list plays an important role in the constructor. For common data members, using the initialization list and assigning values in the constructor has the same effect. In other cases, you can only use the initialization list to initialize members. Otherwise, a compilation error occurs. For example, data members are references, constants, and class objects (the class does not provide constructors without parameters. As follows:
/*******Program 1*********/#include <iostream>using namespace std;class A{     int i;public:     A(){          i = 1;     }     void show(){          cout<<i<<endl;     }};class B{     int i;public:     B():i(1){}     void show(){          cout<<i<<endl;     }};int main(){     A().show();     B().show();}/*******end of Program 1*********/

Output: the constructor of class 11 A does not actually have any difference with the constructor of Class B.

/******* Program 2*********/#include <iostream>using namespace std;class A{     int num;public:     A(int i){          num = i;     }     void show(){          cout<<num<<endl;     }};class B{     int &r;     const double PI;     A a;public:     B(int i){}     void show(){          cout<<r<<endl;          cout<<PI<<endl;          a.show();     }};int e = 5;B::B(int i):r(e),PI(3.1415926),a(i){}int main(){     B(1).show();}/*******end of Program 2*********/

Output result: 53.14159261 if any member in the initialization list is moved to the function body in the constructor of Class B, the following error occurs ::

B: B (int I) {r = E; // This is the reference value, not the initialization Pi = 3.1415926; // The constant value cannot change a = a (I); // before calling the constructor of Class B, the constructor A () of Class A is called first (), at this time, the function is not defined}

4. initialize the list to improve the program running efficiency: Sometimes the assignment between objects is used to replace initialization, instead of displaying the initialization list. This will not cause compilation errors, but will reduce the program running efficiency:
/*******Program 3*********/#include <iostream>using namespace std;class A{     int num;public:     A(){          cout<<"In default constructor"<<end;     }     A(int i){          cout<<"In user-defined constructor"<<end;          num = i;     }     A & operator=(const A& a){          cout<<"Using assignment"<<endl;          num = a.num;          return *this;     }     void show(){              }};class B{     A a;public:     B(int i){}     void show(){          a.show();     }};B::B(int i){     a = A(i);}int main(){     B b(1);     b.show();}/*******end of Program 3*********/
Output result: In default constructorin User-Defined constructorusing assignment1 initialization of member object A is not displayed in the initialization list, before entering the constructor body of Class B, will call the default constructor of Class. In the constructor of Class B, the assignment operation is performed, and the constructor A (INT) of Class A is called to form an unknown object. This method of initializing a member object is not only unclear in the logical structure, but also inefficient. If the constructor B is rewritten to: B (int I): A (I) {}, the output result of the program is :: in User-Defined constructor1 is more efficient.
On the surface, there are many class constructors that do not use the initialization list at all. But in fact, some content will be forcibly added whether or not it is displayed in the initialization list: (1) if this class is a derived class of a class, then the constructor of its direct base class must appear in the initialization list. The programmer can call the constructor of the direct base class in the initialization list. Otherwise, the compiler inserts the default constructor of the direct base class into the initialization list. (2) If the class contains objects of other classes as its data members, the initialization of these objects must be completed in the initialization list. The programmer displays the object constructor in the initialization list. Otherwise, the compiler calls the default constructor of these objects in the initialization list to complete initialization.
5. initialization sequence of member variables: the constructors of the base class are first executed. Other members are initialized in the order they are declared in the class, rather than in the order they appear in the initialization list.
/*******Program 4*********/#include <iostream>using namespace std;class A{     int num;public:     A(int i){          cout<<"In A constructor"<<end;          num = i;     }};class B{public:     int num;     B(int i){          num = i;          cout<<"In B constructor"<<endl;     }};class C{protected:     int num;public:     C(int i){          num = i;          cout<<"In C constructor"<<endl;     }};class D:public C{     A a;     int num;     B b;public:     D(int i):num(i++),b(i++),a(i++),C(i++){}     void show(){          cout<<"C::num="<<C::num<<endl;          cout<<"a.num="<<a.num<<endl;          cout<<"num="<<num<<endl;          cout<<"b.num="<<b.num<<endl;     }};int main(){     D d(1);     d.show();}/*******end of Program 4*********/
Output result: In C construtorin A construtorin
B construtorc: num = 1a. num = 2num = 3B. num = 4
6. in the initialization list, initialization for the array members of the object cannot be completed because the C ++ language does not provide such a mechanism, therefore, the initial values can only be assigned to each element of the member array in the constructor. If the array element itself is an object, this assignment operation will cause a large runtime overhead. More than that. How can I initialize a constant array defined in the class body? In practice, only static constant arrays are defined in the class to complete array initialization. If you really want to define a constant array in the class, a work und is to define a pointer constant pointing to the constant and then initialize it in the initialization list.
/******Program 5*********/#include <iostream>using namespace std;int *CreateArr(int n){     int *p;     p = new int[n];     for (int i=0;i<n;i++)     {          p[i] = i+1;     }     return p;}class A{     int arrsize;     const int* const arr;public:     A(int n):arr(CreateArr(n)){          arrsize=n;     }     void show(){          for (int i=0;i<arrsize;i++)          {               cout<<arr[i]<<' ';          }          cout<<endl;     }         ~A(){          delete[] arr;     }};int main(){     A a(3);     a.show();}/*******end of Program 5*********/
Output result: 1 2 3 because space is actually allocated to ARR in the constructor, this part of space should be released in the destructor of Class ~ A (){
Delete [] arr;
} This ensures no memory leakage.
My original blog address http://licaiqiubzt.blog.163.com/blog/static/2072822482012111093541393/
Related Article

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.