C ++ learning constructor Initialization

Source: Internet
Author: User

As we all know, the job of the constructor is to ensure that each object's data member has an appropriate initial value.

// Assume that name (string), stunum (INT), and grade (INT) are data members of the class myclass. Class myclass: myclass () {name = "Class 1 "; stunum = 60; grade = 2 ;}

I always think that the three rows in the above constructor function are the initialization of the data members. Today, an occasional bug gave me the lead and looked at primer to know that the value assignment is not initialization ......

In fact, the execution of constructor is divided into two phases: 1. Initialization Phase 2. Normal computing phase. (The computing phase consists of all the statements in the constructor's function body. Initialization of member variables takes place before the computing phase !!!)

So how do we initialize the member variables?

1. Through the constructor'sInitialization list, Advocate !!

2. Do not use the initialization list: (1). The member variables of the class type are initialized using the default constructor; (2) built-in types: perform global initialization based on the scope of the variable, local Initialization is not performed.

Note:

1. The initialization list of the constructor is specified in the definition of the constructor rather than in the Declaration.

2. Some variables must be initialized using the initialization list: class type variables without Default constructors, const member variables, and reference type variables

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.