C + + Class member initialization Why do I prefer to initialize the list __c++

Source: Internet
Author: User

Class member initialization can be implemented in constructors or in the initialization list of constructors. But the master is generally choose the latter, what is the reason.

Implementation of the constructor
CMyObject:: cmyobject (int ID, string name)
{
    m_id = ID;
    M_name = name;

Implementation
Cmyobject::cmyobject (int ID, string name) in the initialization list
      : m_id (ID), M_name (name)
{
}

Advantages: Eliminates the presence of temporary objects

Method one is to do assignment in the constructor, and method two is to do the pure initialization operation. As we all know, the assignment operation of C + + will produce a temporary object. The presence of temporary objects reduces the efficiency of the program.


Other scenes:

1. A const member exists in the class, and the member must be initialized in the initialization list.

2. If the class contains other Class B as a member, and Class B prohibits the assignment operation, then the object to B can only be implemented by initializing the 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.