Object initialization in C + +

Source: Internet
Author: User

In C + +, an object is initialized before it is used, and it is always initialized before the object is used.

1. For a built-in type without any members, this must be done manually.

For example:

int x=0;

Double D;

std::cin>>d;

2. Something other than the built-in object, the initialization responsibility falls on the constructor. Make sure that each constructor initializes each member of the object.

For example:

Class Point {...};

Class Point3D

{

Public

Point3D (point Pt,int z);

Private:
Point _pt;

int _z;

};

Point3D::P Oint3d (Point Pt,int z): _pt (PT), _z (z) {}//initialization

Point3D::P Oint3d (point Pt,int z)

{

_pt=pt;

_z=z; These are assignments, not initialization

}

3. Assignment and initialization are different

Assignment: for _pt, the default constructor is called first, and then the new values are immediately assigned to them. (may also copy assignment)

member initial Value column (member initialization list): Directly the copy construct. Increased efficiency.

For _z two methods the same efficiency.

4. When initializing with the member initial column, be aware of it.

C + + has a very fixed sequence of member initialization.

The order of initialization and object declaration are consistent. Instead of the order of the member's initial column, it is guaranteed that the object is initialized before another object by initializing it to another object.

Reprinted from: http://blog.csdn.net/cq20110310/article/details/7265656

Object initialization in C + +

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.