Why does C++ require a user-provided default constructor to default-construct a const object?
In C++, when an object is declared as , it means that once initialized, its value cannot be changed. This presents a problem: if a class does not provide a default constructor, the compiler will synthesize one to initialize the object. However, if the class's member variables lack a default initialization method, this may result in the member variables being in an undefined state.For objects, this state is particularly dangerous because objects, once created, cannot be modified. Therefore, all member variables must be initialized to a valid state from the beginning.Consequently, when working with a object, it is essential to ensure it is correctly initialized from the start. This typically requires providing a default constructor in your class to guarantee all member variables are initialized to a valid state.For example, consider the following class:In this example, the class lacks a default constructor. Attempting to create a object results in a compilation error because there is no suitable constructor to initialize the member.If we modify the class to add a default constructor that initializes , this resolves the issue:In this revised version, we add a default constructor initializing to 0. This ensures objects can be correctly initialized, thereby avoiding undefined states or compilation errors.