Reputation: 163
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?
Upvotes: 1
Views: 418
Reputation: 210455
Just to note: A const
reference does not imply a const
object.
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 through ptrB
, which would violate the const
-ness of the pointer's target.
Upvotes: 2
Reputation: 372814
The reason for this error is that you can put a hole in the type system with it. Consider the following code:
const B dontChangeMe;
B* ptrB = new B();
/* This step is NOT legal. */
const B* &refConstPtrB = ptrB;
/* Uh oh! I now have ptrB pointing at dontChangeMe! */
refConstPtrB = &dontChangeMe;
Consequently, you can't do the assignment that you marked.
Hope this helps!
Upvotes: 1