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