[C++ Primer Chapter 7] The role of the constructor

The role of the default constructor

• Default constructor

The C++ default constructor is a constructor that provides default values ​​for the parameters in the class. In general, it is an empty function with no parameter values, and it can also provide some constructors with default values. If the user does not define a constructor, then compile The compiler will provide a default constructor for the class, but as long as the user customizes any constructor, the compiler will not provide a default constructor. In this case, it is easy to compile an error, so the correct way to write it is that the user When defining the constructor, you also need to add a default constructor, so that it will not cause compilation errors.

Such as: user-defined default constructor

class Test
{
public:
    Test(){} // default constructor
} ;

 

• Why add a default constructor

The reasons are as follows:

1. When the user defines an array, and the element type of the array is object 1 such as class, then the default constructor will be called at this time. If object 1 does not define a default constructor at this time, an error will be reported. But if it is not an object type, it is a built-in data type of C++, and no error will be reported.

Such as: Object array[10];

 

2. When the user defines an array and uses new to dynamically allocate object 1, then if object 1 does not have a default constructor at this time, an error will also be reported, because new will call the parameterless default constructor of object 1 to initialize the object.

如:Object *temp = new Object[10];

 

3. When the user uses the container of the standard library, and the container contains objects such as classes, the default constructor of the object will be called for initialization. If there is no default constructor defined in the class of the object, an error will be reported .

如:vector<Object> vo;

 

4. When a class A takes an object of another class B as a member, if A provides a parameterless constructor but B does not, then A cannot use its own parameterless constructor.

The code below will result in a compile error.

class B
{
    B(int i){}
};

class A
{
    A(){}
    B b;
};

int main(void) 
{
    A a(); // error C2512: 'B' : no appropriate default constructor available

    return 0 ; 
}

 

5. If class A defines a copy constructor, but does not define a default constructor, then if B inherits A, B will call the default constructor of A during initialization, and an error will be reported at this time.

class A
{
    A(const A&){}
};

class B : public A
{
    
};

int main(void) 
{
    B b; //error C2512:'B': no appropriate default constructor available

    return 0 ; 
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324627695&siteId=291194637