According to the C++23 standard, what is the output of this program?
#include <iostream>
struct C {
C() = default;
int i;
};
int main() {
const C c;
std::cout << c.i;
}C lacks a user-provided constructor.
The program has a compilation error
We're trying to default-initialize c. This is not allowed since it is const and C has a defaulted (not user-provided) constructor.
If a program calls for the default-initialization of an object of a const-qualified type
T,Tshall be a const-default-constructible class type or array thereof.
Is C const-default-constructible?
§[dcl.init.general]¶8 again:
A class type
Tis const-default-constructible if default-initialization ofTwould invoke a user-provided constructor ofT(not inherited from a base class) or if— each direct non-variant non-static data member
MofThas a default member initializer or, ifMis of class typeX(or array thereof),Xis const-default-constructible,— if
Tis a union with at least one non-static data member, exactly one variant member has a default member initializer,— if
Tis not a union, for each anonymous union member with at least one non-static data member (if any), exactly one non-static data member has a default member initializer, and— each potentially constructed base class of
Tis const-default-constructible.
C does not have a user-provided constructor (§[dcl.fct.def.default]¶5), and the points below don't apply either.
There are several ways we could make C const-default-constructible:
int i a default member initializer: int i{0}. = default from the constructor, and instead do C::C() = default; separately outside the class definition. This constructor now counts as user-provided.C() {}.