0

I'm new to C++ and is trying to learn the concept of keyword const.

My question is why the object copied to (*p in this example) must have the same LOW level constant as the object copied from (p3 in this example).

I understand that they must have the same low level constant in order for the code to be valid, but I don't understand why this is the case.

What is the reason behind it?

const int *p2;
const int *const p3 = nullptr;
p2 = p3; //ok
int *p = p3; //error: cannot initialize a variable of type 'int *' with an lvalue of type 'const int *const'.
halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137

2 Answers2

4

Let's use a fictional compiler that accepts the assignment.

const int a = 1;

const int *const p3 = &a;
const int *p2 = p3; //ok

int *p = p3; //ok too !

*p = 42;

Oops ! We just modified a, which was const. That's a one-way ticket to UB-Land. This is the reason why you cannot implicitly remove const qualifiers.

Quentin
  • 62,093
  • 7
  • 131
  • 191
  • 2
    Thanks for the great answer! Simple and straight to the point! REally appreciate your help! – Thor Jan 18 '16 at 01:43
2

there is a great answer at this question.

your problem is that const int * means the int is constant, and so you cannot give its address to a pointer which points to a non const int. if he let you do it you would have been able to change the int.
*p = 5; will change a const value.

rustypaper
  • 70
  • 10