Why is a class type member without a default constructor required to be initialized in the initialization list?

Source: Internet
Author: User

noun explanation

1. Default constructor: Constructor for class no parameter or parameter default value is collectively referred to as the default constructor.


2. Initialization list: Unlike other functions, constructors can have initialization lists in addition to names, parameter lists, and function bodies. The list begins with a colon followed by a comma-separated initialization field. A class member is created in the initialization list of the constructor, and at the same time as the class member is created, an initialization value is given to the member variable.




Before explaining why, you need to understand how the constructor performs

The execution procedure of the constructor function

first, the execution of the constructor is divided into three steps. The function's formal parameters are created first (if no formal parameters are omitted), and then the initialization list is executed (even if there is no initial list), and the contents of the function body are executed finally.


When a list is not initialized, the system gives the member an initial value when it creates the class member. The initial values are different depending on the scope of the object. proof of code see Appendix 1

(1) A global object and a local static object, the system assigns an initial value of 0 to a member of type int, and the member of the pointer type assigns the initial value 0x00000000.

(2) The system assigns a random value to a member except for a local object outside the static type.

When the function body is executed, the class member is created and has an initial value. The function body gives the member value instead of initialization, but assigns a value.

This problem can be proved by the following code.

This gives class B a default parameter, so that a member of type B is not initialized in the initialization list of A's constructor.

                                                                                            

#include <iostream> #include <cstdlib>using namespace std;class b{public:b (int data=0): _data (data) {cout << "B ()" << Endl;} B (const b &b): _data (b._data) {cout << "B (const B &)" << Endl;} B & Operator= (const b &b) {cout << "operator=" << endl;_data = B._data;return *this;} ~b () {cout << "~b ()" << Endl;} Private:int _data;}; Class A{public:a (b data = 1) {b = data;cout << "A ()" << Endl;} ~a () {cout << "~a ()" << Endl;} Private:b B;}; int main () {{A A (2);} System ("pause"); return 0;}



When you debug the code above, you can see this in the main function through the this pointer and the window:

1. Create object A with Class A and call the constructor of a.

The constructor of Class A is performed in three steps.

(1) To open up space for the parameters of the constructor, because of the type B object of the formal parameter, the constructor of B is called when the parameter is created.

(2) Executes the initialization list of A's constructor (even if there is no initialization list), creates the member B of object A, and assigns the initial value. Because member B is also a class-type object, B's constructor is called when B is created. When the constructor for B finishes executing, the initialization list for the constructor of a is completed.

(3) The function body that executes the a constructor function. Executes B=data, invokes the assignment operator overload function, and then executes cout << "A ()" <<endl;

The destructor of the parameter data is called when the constructor is finished executing the object in the constructor, because of the parameter. Here, the constructor finishes executing.


2. When object A is created, the scope of a is called, a destructor is invoked, and A's member B also calls the destructor of B.


3, the final execution of the program screen output of the following:


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/7E/72/wKioL1cAogzgQinEAAAwE5ZIteQ869.png "title=" Gouzao.png "alt=" Wkiol1caogzgqineaaawe5ziteq869.png "/>




Why does a class type member without a default constructor be initialized in the initialization list


In the following code, Class B does not have a default constructor, and there is a member of Class B type in Class A

#include <iostream> #include <cstdlib>using namespace std;class b{public:b (int data) {}private:int _data;}; Class a{public:a (int data=0) {}private:b _b;}; int main () {A A;system ("pause"); return 0;}


The above code will error when executed. This is because:

The constructor to execute when creating a type Object A in main (), first creating the formal parameter, and then executing the initialization list.

So here's the problem. To create a member B in the initialization list and give B an initial value, call B's constructor. At this point, because the constructor system does not generate a default constructor, the write constructor must require a parameter, at which point the initialization list does not have parameters that can be supplied to the constructor of B, so an error occurs when creating B.



Members that must be initialized in the initialization list are also:

☆ Constant Member

☆ Reference type member variable.


with the foundation above, it's good to understand that initializing a class member in the initialization list and assigning the initial value, while the constants and reference types of the variables must be created at the time of creation, the constants cannot be changed after they are created, and the reference must be initialized at the time of creation.




Appendix 1:

System default constructor for assigning initial values to members of a class object

#include <iostream> #include <cstdlib>using namespace Std;class test{public:void Display () {cout << "_ p = "<< _p << Endl; cout<< "_data =" << _data << Endl<<endl;} Private:int * _p;int _data;}; Test Test1;int Main () {test test2;static test test3;cout << "test1:" <<endl;test1. Display (); cout << "test2:" <<endl;test2. Display (); cout << "test.3:" <<endl;test3. Display (); System ("pause"); return 0;}


650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7E/75/wKiom1cAoZ3iYcKsAABZ6ML4n-k694.png "title=" Canshu.png "alt=" Wkiom1caoz3iycksaabz6ml4n-k694.png "/>



This article is from the "Newli" blog, make sure to keep this source http://15129279495.blog.51cto.com/10845420/1759816

Why is a class type member without a default constructor required to be initialized in the initialization list?

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.