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;
}
Constructors may be declared as inline , explicit , friend , or constexpr . A constructor can initialize an object that has been declared as const , volatile or const volatile . The object becomes const after the constructor completes.
Yes, you can also initialize these values using the constructor.
To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.
Copy Constructors is a type of constructor which is used to create a copy of an already existing object of a class type. It is usually of the form X (X&), where X is the class name. The compiler provides a default Copy Constructor to all the classes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With