There’s something I don’t quite understand with how references are handled in C++:
B objB = B(); // Regular B object
const B &refConstObjB = objB; // Reference to const B object
B* ptrB = new B(); // Regular pointer to B
B* const &refPtrConstB = ptrB; // Reference to const pointer to B
All of the above compiles just fine. However the following doesn’t:
const B* &refConstPtrB = ptrB; // Reference to pointer to const B
Considering both the object and the pointer were declared as non-const, why can I reference the object as a const object, but can’t do the same with the pointer?
Just to note: A
constreference does not imply aconstobject.It simply means an object that is read-only through that reference. So whether or not an object is
const, you can have a read-only reference or pointer to it.Now, if what you mentioned were allowed, you could say
refConstPtrB = pointer_to_some_const_B, and then mutate that object throughptrB, which would violate theconst-ness of the pointer’s target.