C + + Constructors Initialize class member variables using the difference between the initialization list and the direct assignment within the constructor

Source: Internet
Author: User

Initialization and assignment do not make much difference to members of built-in types, like any constructor.

But sometimes you have to use a constructor with an initialization list :


(1) The member type is classes without a default constructor。 If no explicit initialization is provided, the compiler implicitly uses the default constructor of the member type, and if the class does not have a default constructor, the compiler attempts to use the default constructor will fail.



(2) A const member or a member of a reference type . Because const objects or reference types can only be initialized, they cannot be assigned a value.




Another number of assignments, the difference in efficiency:

Initialize the list of parameters assigns a value to a member variable at the time the object is initialized.

Directly within the constructor, assigning a value of two times to the member variable. Once the object construct is assigned with the default value, and the second is to call the constructor to assign the value

It is obvious that the constructor initializes the list with a higher efficiency


So I don't know if it's a good programming habit to use the initializer list in a constructor? The big God knows the message to know the small white bar

C + + Constructors Initialize class member variables using the difference between the initialization list and the direct assignment within the constructor

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.