1

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?

1
  • By the way, my variable names are wrong! refConstPtrB and refPtrConstB should be inverted. Commented Apr 5, 2012 at 3:07

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I see! Declaring refConstPtrB give us no guarantee that the data that is being pointed is constant. I would have to declare a pointer to a constant B object for refConstPtrB to be legal. I should have spotted this! Oh well, I guess I'm tired!
1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.