Let's say we have a class called object.
int main(){ object a; const object* b = &a; (*b); }
Question: b is a pointer to const, but the object it is pointing to is actually not a constant object. My question is, when we dereference the pointer "b" why do we get a constant object instead of what it is actually pointing at which is normal non constant object.
Because that's how the built-in dereference operator *
works in C++. If you dereference a pointer of type T *
, you get an lvalue of type T
. In your case T
is const object
.
Neither *
operator, not the pointer itself cares (or knows) that the object the pointer is pointing to is actually non-constant. It just can't be any other way within the concept of static typing used by C++ language.
The whole purpose of const-qualification at the first (and deeper) levels of indirection is to provide you with an ability to create restrictive access paths to objects. I.e. by creating a pointer-to-const you are deliberately and willingly preventing yourself (or someone else) from modifying the pointee, even if the pointee is not constant.
The type of an expression is just based on the declared types of the variables in the expression, it can't depend on dynamic run-time data. For instance, you could write:
object a1; const object a2; const object *b; if (rand() % 2 == 0) { b = &a1; } else { b = &a2; } (*b);
The type of *b
is determined at compile-time, it can't depend on what rand()
returns when you run the program.
Since b
is declared to point to const object
, that's what the type of *b
is.
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