Search code examples
c++pointersreferenceconstants

const reference to a pointer


When I have a const reference to a pointer, how come I am able to change the value of the object the pointer points to, does the const means in this example, address stored in pointer cannot be changed as the reference is a const. but we can change the value of the object the pointer points through the reference

#include <iostream>

int main(){
    int n = 5;
    int *ptr = &n;
    const auto &refOfPtr = ptr; 
    *refOfPtr = 10;
    std::cout << n << std::endl;
    
}
Output : 10

Solution

  • You have a const reference to the pointer, so you can't change where it points. I.e. the type of refOfPtr is int * const &, a reference to a const pointer to (mutable) integer.

    But it points to a mutable object, so you can change the content of that object through this pointer.