Search code examples
c++constructorconstantsdefault-constructor

Compiler complaints for const object not initialized


Possible Duplicate:
uninitialized const

I understand that a const object needs to initialized.

So for the following code,

class sample
{};

int main()
{
   const sample obj;
   return 0;
}

the compiler will complain because the const object obj is not initialized.

But when i modify the code(show below) with a default constructor, the compiler will not throw any error.

class sample
{
    public:
       sample() { }
};

int main()
{
    const sample obj;
    return 0;
}

What is the thing that the newly added default ctor does which satisfies the compiler?


Solution

  • What is the thing that the newly added default ctor does which satisfies the compiler?

    Because that is the requirement imposed by the C++ standard when declaring objects with the const qualifer.

    Reference:

    C++03 8.5 Initializers 8 Declarators
    §9:

    If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor. Otherwise, if no initializer is specified for a nonstatic object, the object and its subobjects, if any, have an indeterminate initial value90); if the object or any of its subobjects are of const-qualified type, the program is ill-formed.