Reference documents:
1. Huang Bongyong Handsome
2.http://www.cnblogs.com/graphics/archive/2012/10/02/2710340.html
3.http://blog.csdn.net/pnhuangyu/article/details/12352073
Divided into three parts:
First, the basic
Second, when to need the default constructor
Third, the default constructor initializes the member to what value
First, the basic
1. Constructors without parameters are default constructors, with only one default constructor.
2. If the user does not declare the constructor themselves, C + + will provide a default constructor. However, if the user declares the constructor themselves, C + + no longer provides a default constructor. At this point, if the user does not declare a default constructor themselves, an error occurs when declaring A;
3. Do not use the statement Hyong A () when the default constructor is defined, because the compiler will interpret a as a function that returns type Hyong, without initializing object A, the correct statement should be Hyong A=hyong ();
4. A constructor with only one argument, such as Hyong (int a), can be called with a statement hyong x=6.
When you need a default constructor ① an object array ② a container of a standard library, if the element type inside the container is an object of a class ③ the class has a member of another class when the ④ class inherits
When a Class A is a member of an object of another class B, if a provides a parameterless constructor and B does not, then a cannot use its own parameterless constructor. The following code causes a compilation error.
class b{ public : B ( int x) {A = X;} int A;}; class a{ public : int A; b b;}; int main () {A CA; // error because B has no default constructor return 0 ;}
Class A defines a copy constructor, not a default constructor, b inherits from a, so B invokes A's constructor to initialize a when initializing, and a does not have a default constructor, resulting in a compilation error.
class a{ A (const a&) {}}; class Public a{ }; int Main (void) { //error C2512: ' B ': no appropriate default Constructor available getchar (); return 0 ; }
Third, the default constructor initializes the member to what value
This mainly depends on the following three points:
(1) The type of the data member itself;
(2) The scope range of the generated class object (local object and global object);
(3) A special static data member. The static members are not discussed here, and after writing a special article about
For variables of class type, regardless of the global scope or local scope, their constructors are called to initialize.
For built-in, compound variable types, such as int, char *, and so on, the local scope is not initialized, and the global scope is initialized, typically set to 0.
Example:
#include"stdafx.h"#include<string>usingnamespacestd;classtest{ Public: intA; BOOLb; CharC; DoubleD; string S;}; Test T2; int_tmain (intargc,_tchar*argv[]) {Test T; return 0;}
Results:
The "C + +" default constructor