C + + constructors and destructors

Source: Internet
Author: User
Tags shallow copy

Transfer from http://blog.csdn.net/tqtuuuu/article/details/6652144

constructor function

For C + + constructors, it is divided into the following categories:

1. Default constructors

2. Hermit conversion constructor

3. Copy Constructors

4. Other constructors

1. The default constructor represents a constructor that does not have any parameters, and when any constructor is customized, the default constructor is no longer automatically created and, of course, the default constructor does nothing, and the programmer's concern coefficients plummet. A concern about the default constructor is that when this class inherits from another class (that is, the parent class), the parent class does not have a default constructor, this class will automatically have no constructors, and must also define a constructor that can at least support the initialization of the parent class.

2. What happens when a hermit transforms a constructor? It is a class of constructors that contains only one parameter. Because of the C + + specification, a hermit transformation is automatically defined for a constructor that contains only one parameter, converting an object of the constructor's parameter to the data type to a class object. As shown in the following example:

1 class String {2      String (constChar *s); 3 }; 4 5 " Hello friends ";

Where the string "Hello friends" is converted through the Hermit transformation constructor to the string class object S. Here has to mention a key word explicit, compared to the tragedy of a few years after learning C + + to know such a key word, which also fully embodies the importance of a good book. Let's take a look at the usage of explicit, and then explain.

1 classString {2     ExplicitString (Const Char*s);3 };4 5String s ="Hello friends";//compilation does not pass6 7String S ("Hello friends");//compiled by

Explicit is only used for constructors and is only used for hermit conversion constructors, and is intended to prohibit the hermit constructor function. As shown in the code above, when you add the explicit keyword to the constructor, String s = "Hello friends"; compilation does not pass. Of course, the constructor itself is still working properly at this point.

3. A copy constructor is a special constructor that is used to copy objects. It allows you to initialize a homogeneous object that is being created by using an already created object (specified by the parameters of the copy constructor).

1 class class name 2 {3public:4     class name (class name & object name); 5 };

As described in the preceding code, the copy constructor can have only one parameter and must be a reference to the same object. Each class should have a copy constructor, and if the user does not specify it, the default copy constructor will be used. The default copy constructor performs a copy of the entire contents of the object, but sometimes it needs to be copied selectively and in a different way. In this case, you need to display the definition copy constructor and implement the copy for the part of interest or add some property values for the new object.

The most common use of copy constructors is when you have pointer-type attributes in a class, because the default copy function is a copy-by-reference, a so-called shallow copy. You need to display the Define copy constructor and display the pointer from the new memory and copy the previously pointed value into the newly allocated memory.

4. The other constructors, nothing special, are the constructors that are not included in the preceding and above-mentioned classes.

Constructor initializes a list of parameters

You need to use the Initialize member list in the following situations: (to be added)

First, the data member that needs to initialize is the case of the object;

Second, the class member that needs to initialize the const adornment;

In the first case, if a property in Class A has a Class B, and Class B does not have a constructor that does not have a parameter, the initialization of a is also required to initialize B, so the parameter list needs to be initialized. Of course, in this case, the general member property can also be initialized in this way.

In the second case, the Const member property cannot be copied and cannot be changed once initialized.

The following example illustrates the use of constructor initialization parameter lists:

1#include <iostream>2 using namespacestd;3 4 classB5 {6  Public:7Bintb) {8cout<<b<<Endl;9     }Ten }; One  A classA - { -  Public: the b b; -AintAintci); - Private: -     Const intci; +     //const int CI = 10; //Compile error, cannot initialize -     Static Const intCV =Ten;//after adding the static keyword, you can compile the +     intC; A }; at  -A::a (intAintCI): B (A), Ci (CI), C (4) { -cout << ci <<"--"<< C <<Endl; - } -  - intMain () in { -A A (5,Ten); to     return 0; +}

Destructors

The destructor corresponds to the constructor function and does some aftercare when the object dies. Look at the following example:

1#include <iostream>2 using namespacestd;3 4 classA5 {6  Public:7 A () {8cout <<"A ... .."<<Endl;9     }Ten~A () { Onecout <<"~a"<<Endl; A     } - }; -  the classD | PublicA - { -  Public: - B () { +cout<<"B ....."<<Endl; -     } +~B () { Acout<<"~b"<<Endl; at     } - }; -  - intMain () { -A *a =NewB (); -     DeleteA; in  -     return 0; to}<span style="font-family:arial, Verdana, Sans-serif white-space:normal; Background-color:rgb (255, 255, 255);">&nbsp;</span>

Compile output:

1 #./a. Out2a ... 3 B ..... 4 ~a

Thus, when object a dies, the destructor of object A is automatically called. But C + + is too silly, clearly I instantiate the B object, but why is the destructor called the destructor of a object? By looking at Delete a, you can estimate that the DELETE keyword only recognized the object of a, without being flexible. How can this ...

Virtual keyword

The above example shows that the object B is constructed, but there is no destructor, what is the problem? Anyway, I'm not sure. So the virtual keyword provided by C + + can solve this problem, see the following code:

1#include <iostream>2 using namespacestd;3 4 classA5 {6  Public:7 A () {8cout <<"A ... .."<<Endl;9     }Ten     Virtual~a () {//The only difference: Add the keyword virtual Onecout <<"~a"<<Endl; A     } - }; -  the classD | PublicA - { -  Public: - B () { +cout<<"B ....."<<Endl; -     } +~B () { Acout<<"~b"<<Endl; at     } - }; -  - intMain () { -A *a =NewB (); -     DeleteA; in  -     return 0; to}

Output:

1 #./a. Out2a ... 3 B ..... 4 ~B5 ~a

As can be seen, after adding the virtual keyword, it is true that the problem is resolved, and the B object also calls the destructor. But why is that?

The following start yy, maybe delete is not so silly, she will go to the virtual function table to see if the current destructor is defined as virtual function, if it is a virtual function, it will think, that object will not instantiate the object of the subclass, and then determine whether to instantiate as a subclass object, If it is, the destructor of the subclass is called first.

C + + constructors and destructors

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.