Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing a pointer to constant

Tags:

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.

like image 554
Ashim Avatar asked May 22 '18 02:05

Ashim


2 Answers

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.

like image 190
AnT Avatar answered Oct 15 '22 00:10

AnT


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.

like image 33
Barmar Avatar answered Oct 15 '22 00:10

Barmar