I heard that const members must be explicitly intialized, but the following compiles for me:
class someClass
{
int const x;
};
int main()
{
return 0;
}
I heard that const members must be explicitly intialized, but the following compiles for me:
class someClass
{
int const x;
};
int main()
{
return 0;
}
Try this:
int main()
{
someClass obj;
return 0;
}
Since you haven't instantiated your object, your compiler didn't throw an error. You probably know the right way to initialize x
but I'm putting it down just in case.
class someClass
{
int const x;
public:
someClass():x(10){}
};
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, someClass
has 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 any someClass
object, 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,
class someClass
{
someClass() { } // error, does not initialize const-qualified x
int const x;
};
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.