The C + + constructor initializes the class member variable, 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 a class that has no 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.




There is also a difference in the number of assignments, the efficiency:

Initializes a parameter list to assign a value to a member variable at the time the object is initialized,

Constructors are assigned 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 don't know if it's a good programming habit to use the Initialize parameter list in a constructor? The big God knows the message to know the small white bar

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The C + + constructor initializes the class member variable, 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.