Constructors--Default constructors

Source: Internet
Author: User

Each class defines the way in which his objects are initialized, and the member functions that control their object initialization are called Constructors .

The difference from other functions is that: 1, the constructor does not return a value . 2, cannot be declared as const, because when you create a const object, you know that the constructor completes the initialization process, the object can actually get its "Const" property, so the constructor in the const object construction process is able to write value to it.

When a class does not have a constructor defined, the compiler implicitly synthesizes a constructor called the composition's default constructor . The initialization order is initialized with the initial values within the class, with no initial value, and then the default initialization is performed. Note The default constructor for a composition is only available if no constructors are defined. Like what

class TT {    int  tmp;  Public :    TT (int  i) {        = i;     New TT (1); // OK New TT (); // No matching constructors

There are three situations in which you cannot rely on a composite constructor:

The first of these is as above.

The second is to define values that are undefined when some members within a class perform default initialization, such as pointers, arrays, and so on.

The third is that some classes cannot synthesize default constructors, such as a member of a class that does not have a default constructor.

So we need to define our own default constructors. In c++11, you can use "=default" to represent the default behavior and add the following code to the class:

TT () = default;

Of course, you can declare within a class, define default outside of the class, except that the class definition is inline by default, and the out-of-class definition is not inline.

Constructors--Default constructors

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.