In the default constructor of the C++ class, count the details you don’t know

1. Under normal circumstances, the compiler will generate a default parameterless constructor for the class

As shown in the figure, an empty class Man is defined, the main function below declares a Man object man, and no error is reported when running the compiler. Prove that the compiler created a default no-argument constructor for us
Insert picture description here

2. When we create a parameterized structure for the class, the compiler will not generate a default parameterless structure for us

Man man; The compiler reported an error in such a declarative way. Prove that the compiler does not survive the default no-argument constructor for us.
Insert picture description here

If we need to use a parameterless constructor, we can only write a parameterless constructor ourselves
Insert picture description here

3. If you don't want the compiler to generate a default constructor for us, we can refuse like this

Insert picture description here
Write the parameterless constructor under private so that it cannot be called outside the class, which is equivalent to the compiler not providing us with a parameterless default constructor.

4. If no constructor is defined in a class, the compiler will only provide a default constructor in these three cases

1. If the class has virtual member functions or virtual inheritance from the parent class (ie, there is a virtual base class);
2. If the base class of the class has a constructor (it can be a user-defined constructor or a default constructor provided by the compiler) );
3. All non-static object data members in the class have constructors in the class to which they belong (can be user-defined or the default constructor provided by the compiler).

You must think that it includes everything.
Okay, here are some counterexamples
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_50188452/article/details/115245024