I heard that const members must be explicitly intialized, but the following compiles for me:
class someClass
{
int const x;
};
int main()
{
return 0;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If a class has const-qualified member variables, then for any constructor defined for that class, those variables must be initialized in the constructor initializer list. If any defined constructor does not initialize a const-qualified member variable, the program is ill-formed.
In your example code,
someClasshas no user-declared constructors, so there is an implicitly declared default constructor. However, if that constructor is not used, then it is not defined. Since you do not instantiate anysomeClassobject, the constructor is not used. Hence, your example code does not have any errors.If you were to define a constructor for the class and not initialize the const member,
or if you were to instantiate an instance of
someClass(which would cause the implicitly declared default constructor to be defined), then the program would be ill-formed.