An important note about the C++ default constructor

  • 2020-05-10 18:34:06
  • OfStack

Most C++ books say that the compiler automatically generates the default constructor when we don't define it ourselves. Actually this sentence I 1 straight also

No doubt about it. But recently, I have read some information and gained a new understanding.

In fact, I think most C++ books are playing with words. If the compiler automatically generates the default constructor for us

The default construct is a class that does nothing, which means that there is no actual code work in the constructor generated by the compiler by default

Building is optional, so the compiler actually generates the default constructor for each class.

In the in-depth exploration of the C++ object model, we talked about four cases in which the compiler automatically generates default constructors, and the default constructs generated in these four cases

Inside the build function is operated by the actual implicit code:

1. If the class A member contains an object of class B, and class B also shows the definition of a constructor, the compiler will generate a default constructor when the class A object is generated, and the code to call the class A constructor is provided in the default constructor.


2. If class B inherits from class A, and class A shows that a constructor is defined, the compiler will also generate a default constructor during the generation of class B objects, in which the code to call the base class A constructor is provided.


3. If a class contains virtual functions, the compiler automatically generates a default constructor to provide initialization related to virtual table Pointers.


4. If a class falsely inherits from another class, the same compiler generates the default constructor for that class.


Except for the above four cases, the compiler does not produce the default constructor, because even if the compiler produces the default constructor, but there is no real content in the default constructor, then the default constructor is meaningless, so let's say the compiler does not produce it.


Related articles: