How do I define a constant in C++, that points to a mutable object?
If I declare
static const CMyClass* IMPL;
and assign
const CMyClass* CSomeClass::IMPL = new CMyClass;
then I can only call const
functions on the object. Its internals are locked. This is not what I want.
If I leave off the const
qualifier, I can reassign the pointer IMPL
, so it isn’t protected as a constant anymore, which it should be. final
seems to be applicable only to functions in C++. Is there an equivalent to a Java’s final
variables in C++?
You have to place the const
at the right place in the declaration. The rule is: const
applies to the thing immediately to the left, unless it's at the left edge itself, when it applies to the right.
Therefore, these two are (mutable) pointers to a constant integer:
const int * p;
int const * p;
This is a constant pointer to a (mutable) integer:
int * const p;
And these are constant pointers to a constant integer:
const int * const p;
int const * const p;
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