Turn from: Click to open the link
The default constructor refers to a constructor that provides a default value for all parameters, usually a parameterless constructor. For example, the following class test, whose default constructor is test ().
Class Test
{public
:
Test () {}//default constructor
};
If you do not provide any constructors for your class, the compiler will automatically generate a default parameterless constructor for you. Once you have defined a constructor for your class, even if it is only one, then the compiler will no longer generate the default constructor.
Class A
{public
:
A (int i): num (i)
{
cout<< "constructor a" <<endl;
}
Virtual ~a ()
{
cout<< "destructor A" <<endl;
}
virtual void Fun_const1 () {cout<< "Fun_const1 A, num is:" <<NUM<<ENDL;}
};
Class B:public A
{public
:
B ()
{
cout<< "constructor B" <<endl;
}
~b ()
{
cout<< "destructor B" <<endl;
}
void Fun_const1 () {cout<< "Fun_const1 B, num is:" <<NUM<<ENDL;}
}; <span style= "color: #ff0000;" >
</span>
Here B prompts that a does not provide a default constructor (A has a non-default constructor, so the compiler does not generate the default)
Turn from: Click to open the link
Several other scenarios that generate a default constructor are:
The first is that a class member is a class object, and the Member's class contains a default constructor, and the C + + compiler will also generate a default constructor for the class that invokes the constructor of its member object to complete the initialization of the member. It should be emphasized that if the class of this member does not give a default constructor, then the C + + compiler will not help you generate the default constructor for the class.
The second scenario is that the base class for this class has a default constructor. The C + + compiler will also help you generate the default constructor for the derived class to invoke the default constructor of the base class, which completes the initialization of the base class. In addition, it must be emphasized that if the base class does not provide this default constructed function, then the C + + compiler does not generate a default constructor for the derived class (this includes two layers of meaning, first, the base class has no form constructor; second, the base class has other forms of non-default constructors, of course, This type is not compiled, and the truth is obvious.
The third scenario is that a virtual function exists in the class, and the C + + compiler generates a default constructor for you to initialize the virtual table (vftable of the virtual function table).
The fourth case is the existence of a virtual base class, then the C + + compiler will generate a default constructor for you to initialize the Virtual base class table (Vbtable).