rosshjb
rosshjb

Reputation: 659

Declaring a const object in C ++ requires a user-defined default constructor. If I have a mutable member variable, why not?

In C++, to declare an object of a class that has a member variable as const, we must have a user-defined default constructor. The following code illustrates this.

class Some {
    int value;
};

int main() {
    // error: default initialization of an object of const type 'const Some'
    //        without a user-provided default constructor
    const Some some;

    return 0;
}

However, if a member variable owned by a class is qualified as mutable, the compiler will not report any errors. For reference, I compiled using the command clang++ -std=c++17 -stdlib=libc++ helloworld.cpp -o helloworld.out --debug. I wonder if this result is due to a bug in the compiler or according to the syntax defined in the C++ language.

class Some {
    mutable int value;
};

int main() {
    const Some some;

    return 0;
}

Upvotes: 8

Views: 1616

Answers (1)

Moshe Gottlieb
Moshe Gottlieb

Reputation: 4013

Rewriting my comment as an answer, hope it could helps someone.

It makes no sense declaring a const object if it is not initialized in some form.
Consider the following code:

    const int x;

clang says: error: default initialization of an object of const type 'const int'.
gcc would say: error: uninitialized const ‘x’ [-fpermissive]

The logic behind this is that there is no sense in this type of declaration.
The value of x can never change, and therefore this code would be unpredictable as x would be mapped to uninitialized memory.
In your example, adding the keyword mutable to value means that although the Some instance is constant when declared as:

    const Some some;

It is still possible to change value at a later time.
For example:

    some.value = 8;

This means it is possible to use this code in a predictable manner, since value can be set later, and there are no uninitialized constants.

Upvotes: 3

Related Questions