I have learnt about constexpr variables in c++ and read that int i =0; constexpr int j = i; fails because i is not a constant expression which makes sense. But then when I did the same with a variable of a class, it worked.
struct C{};
int main()
{
int i = 0; //i is not a constant expression as expected
//constexpr int j = i; //this fails AS EXPECTED
C c;
constexpr C d = c; //WHY DOESN'T THIS FAIL??
}
As you can see, constexpr C d = c; compiles without any problem unlike constexpr int j = i; even though c is also not a constant expression.
I want to know the reason behind this.
Because the class
Chas an implicitconstexprcopy constructorconstexpr C::C(const C&)that can be used in constexpr context like this.Basically the initialization
constexpr C d = c;is a constexpr context and the constexpr ctors are designed exactly for these purposes.You can also see this by looking at the generated code at cppinsights:
As we can see in the above generated code,
Chas implicitly declaredconstexprconstructors that can be used in constexpr contexts.From constexpr: