cause of Object initialization list
1) If we have a class member, which is itself a class or a struct, and this member has only one constructor with parameters, there is no default constructor. In order to initialize this class member, you must call the constructor with the parameter of the class member, and if there is no initialization list, then he will not be able to complete the first step and will error.
2) When a class member contains a const object, or a reference, they must also be initialized through the member initialization list, because the two objects are initialized immediately after the declaration, and in the constructor, they are assigned, and this is not allowed.
#include <iostream>usingNamespace Std;class a{ Public:A(int_a) {a = _a; cout <<"Constructors"<<"a"<< a << Endl; } ~a () {cout <<"destructor"<<"a"<< a << Endl; }protected:Private:intA;};/* Initialization list of constructors resolves: a Class A object is combined in Class B (a class designed a constructor) */Class b{ Public:B(int_B1,int_B2):A1(1),A2(2),C(0) {} B (int_B1,int_B2,intMintN): A1 (M), A2 (n), C (0) {B1 = _b1; b2 = _b2; cout <<"B-Constructor"<<endl; } ~b () {cout<<"B's destructor"<<endl; }protected:Private:intB1;intB2; A A2; A A1;Const intc;};//Execute the constructor of the grouped object first//If there are multiple groups of objects, in order of definition, instead of the order in which the list is initialized//destructor: Opposite to the constructor's call order//The constructed order of the grouped objects is related to the order of definition, which is not related to the order of the initialization list.The //initialization list is used to assign a value to the Const propertyvoidObj10play () {//a A1 (ten); //b Ojbb (1, 2); //1 parameter PassingB ojbB2 (1,2,3,4);//2 Call Order return;}voidMain100 () {obj10play (); System"Pause");}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + + constructor initialization list