C + + constructors

Source: Internet
Author: User

The job of the constructor is to ensure that the data members of each object have appropriate initial values.

Definition of a constructor function

(1 ) constructors can be overloaded.

There is no limit to the number of constructors that can be declared for a class, as long as the formal parameter list for each constructor is unique.

(2 ) arguments determine which constructor to use.

(3 ) constructor is executed automatically.

Whenever you create an object of that type, the compiler runs a constructor.

(4 ) constructors cannot be declared as Const.

When you create a const object of a class type, run a generic constructor to initialize the const object. The work of the constructor is to initialize the object, which is initialized with a constructor, regardless of whether the object is const.

Second, constructor initialization type

The constructor can contain a list of initialization.

Sales_item::sales_item (conststring & book):     ISBN (book), Units_sold (0) , Revenue (0.0) {}

Note: constructors can be defined inside or outside a class. The constructor initialization list is specified only in the definition of the constructor, not in the declaration.

Constructor initialization lists one reason that is difficult to understand is that omitting the initialization list and assigning values to data members in the function body of the constructor is legal.

Sales_item::sales_item (conststring & book) {    = Book ;     0 ;     0.0 ;}

The above constructor assigns a value to a member, but does not display initialization.

Attention:

(1) regardless of whether there is an explicit initialization, the ISBN member is initialized before the constructor is executed. This constructor implicitly initializes an ISBN using the string default constructor. When executing the function body of a constructor, the ISBN member already has a value that is overridden by an assignment in the body of the constructor function.

(2) The constructor is executed in two stages: 1) initialization phase, 2) normal calculation stage. The calculation phase consists of all the statements in the body of the constructor function.

(3) data members of a class type are always initialized in the initialization phase, regardless of whether the member displays initialization in the constructor initialization list. Initialization occurs before the start of the calculation phase.

(4) each member mentioned in the constructor initialization list is not shown, and will be processed as follows: If it is a class type, run the type default constructor to initialize the member of that type, and if it is a built-in type, it depends on the scope of the object. They are initialized to 0 in the global scope and are not initialized in the local scope.

1 . Sometimes a constructor initialization list is required.

If no initialization is provided for a class member, the compiler implicitly initializes the member with the member's default constructor. If the class does not have a default constructor, the compiler attempts to use the default constructor will fail. In this case, an initialization must be provided in order to initialize the member.

Attention:

(1) Some members must be initialized in the constructor initialization list. For such members, assigning values to them in the constructor function body does not work. A member of a class type without a default constructor, and a member of a const or reference type, regardless of type, must be initialized in the constructor initialization list.

(2) in addition to two cases, assigning values to data members of non-class types or using initializers is equivalent to both results and performance. The following constructor is an error.

classconstref{ Public: Constref (intII);Private:    inti; Const intCI; int&Ri;}; Constref::constref (intII) {i= II;//OKCI = II;//cannot assign a value to constRI = i;//}

You can initialize objects of a const object or reference type, but you cannot assign values to them. The only chance to initialize a const or reference type data member is in the constructor initialization list. The following constructor is correct.

Constref::constref (int II): I (ii), CI (ii), RI (ii) {}

Note: in many classes, initialization and assignment are strictly inefficient: The data member may have been initialized directly and initialized and assigned to the value. More important than the efficiency issue is that some data members must be initialized.

2, the member initialization order.

Each member can be specified only once in the constructor initialization list. The constructor initialization list specifies only the values that are used to initialize the member, and does not specify the order in which the initialization is performed. The order in which members are initialized is the order in which members are defined.

Note: The order of initialization is often irrelevant. However, if a member is initialized based on another member, the order in which the member is initialized is critical.

class x{    int  i;     int J;  Public :    X (int  val): J (Val), I (j) {}};

The effect of this initialization list is to initialize I with a J value that has not been initialized.

Note: It is a good idea to write a constructor initialization list in the same order as the member declaration. Also, avoid using members to initialize other members as much as possible.

3 . Initialization can be an arbitrary expression.

An initializer can be any complex expression.

Sales_item (conststringintdouble price ):     * price) {}

4 . Initialization of data members of class type.

When you initialize a member of a class type, you specify the argument and pass it to a constructor of the member type. You can use any constructor of that type.

Sales_item (): ISBN (9'), Units_sold (0), Revenue (0.0) {}

Third, the default real participation constructor

Use the default arguments to reduce code duplication.

Iv. Default Constructors

The default constructor is used whenever an object is defined without an initialization. A constructor that provides default arguments for all parameters also defines a default constructor.

1, the composition of the default constructor.

Even if a class defines only one constructor, the compiler will no longer generate a default constructor. The compiler automatically generates a default constructor only if a class does not have a constructor defined.

Attention:

(1) the composition's default constructor initializes the member with the same rules as the variable initialization. Members that have class types are initialized by running their respective default constructors. Members of built-in and composite types are initialized only for objects that are defined in the global scope.

(2) If a class contains a member of a built-in or composite type, the class should not rely on the composition's default constructor. It should define its own constructors to initialize these members.

2, A class should typically define a default constructor.

In some cases, the default constructor is implicitly applied by the compiler. If the class does not have a default constructor, the class cannot be used in these environments. For example: The NoDefault class does not have a default constructor and has a constructor that accepts string arguments.

(1) each constructor for a class with a NoDefault member must display the initialization NoDefault member by passing an initial string value to the NoDefault constructor.

(2) the compilation period does not synthesize a default constructor for a class that has a NoDefault type member. If such a class wants to provide a default constructor, it must be explicitly defined, and the default constructor must explicitly initialize its NoDefault member.

(3) The NoDefault type cannot be used as an element type for dynamically allocating arrays.

(4) The statically allocated array of type NoDefault must provide a display initialization for each element.

(5) If you have a container that holds the NoDefault object, you cannot use a constructor that accepts a container size without providing an element initializer.

Note: It is common to provide a default constructor that is always true if other constructors are defined. The initial value provided to the member in the default constructor should indicate that the object is "empty".

3 . Use the default constructor.

= Sales_item ();

Both of these are the correct ways to define an object using the default constructor.

C + + constructors

Related Article

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.