views:

94

answers:

2

I heard that const members must be explicitly intialized, but the following compiles for me:

class someClass
{
    int const x;
};

int main()
{
    return 0;
}
+4  A: 

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){}
};
Jacob
+6  A: 

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.

James McNellis
@James: I think you meant "define a constructor"?
Jacob
@Jacob: Destructor... constructor... same thing, right? :-O Thanks for the correction.
James McNellis
@James: Lol, no problem :)
Jacob