let's have an example program:
struct Example
{
int* pointer;
Example(int* p) : pointer(p) {}
};
int main()
{
int var = 30;
const Example object(&var);
object.pointer = &var; // error
*object.pointer = var;
}
I do know why the error appears - when creating a const Example object, pointer is actually const pointer, not a pointer to const. Therefore, when assigning &var to object.pointer it is not correct but assigning var to the *object.pointer works perfectly fine.
So is there any way to make this line:
*object.pointer = var;
not compile? I want the value that pointer points to to also be const. In other words, when creating a const object:
const Example object(&var);
I want constness to be applied also on the value itself, not only on the pointer:
const int* const pointer; // something like that
This creates a
constobject. Once aconstobject is created it cannot be changed. This is what a constant object means, by definition.This attempts to change this object's member. This object cannot be changed. It is a constant object now, hence the error.
"Something like that" declares a
pointerthat's both a constant value itself, and it points to a constant value.If you want an object with a pointer to
const int, that would be:And making the object itself constant has absolutely nothing to do with it, whatsoever. It only prevents modification of the object itself. Once you make something
constit cannot be changed for any reason.