Why do I get an error when I run this? I was expecting ptr_ref to be unable to modify the address in which ptr is pointing to but things don't appear to be going as planned.
int b = 3;
int* ptr = &b;
//says something about cannot convert int* to type const int*&
const int*& ptr_ref = ptr;
Thanks in advance, 15 yr old C++ noob
Constant Pointers A constant pointer in C cannot change the address of the variable to which it is pointing, i.e., the address will remain constant. Therefore, we can say that if a constant pointer is pointing to some variable, then it cannot point to any other variable.
A pointer in C++ is a variable that holds the memory address of another variable. A reference is an alias for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable. Hence, a reference is similar to a const pointer.
The grammar doesn't allow you to declare a “const reference” because a reference is inherently const . Once you bind a reference to refer to an object, you cannot bind it to refer to a different object.
No. A reference is simply an alias for an existing object. const is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r .
ptr_ref
is declared not as a const
reference to pointer to int
, but rather a reference to pointer to const int
, so you have a type mismatch. You would have to do
int* const& ptr_ref = ptr;
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