Thor
Thor

Reputation: 10038

Why the object copied to must have the same LOW level of constant as the object copied from?

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'.

Upvotes: 0

Views: 46

Answers (2)

rustypaper
rustypaper

Reputation: 100

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.

Upvotes: 2

Quentin
Quentin

Reputation: 63124

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.

Upvotes: 4

Related Questions