Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

assign pointer to constant pointer in c++

I have a constant pointer cp that points to A and a non constant pointer p that points to B. I wold say that I can assign cp to p, i.e. p=cp because in this way both cp and p point to A and I cannot do the opposite: cp=p, because in this way I am saying that cp should point to B but cp is a constant pointer so I cannot change what it is pointing to.
I tried with this simple code but the result is the opposite, can someone explain me what is the correct version please?

std::vector<int> v;
v.push_back(0);
auto cp = v.cbegin(); // .cbegin() is constant 
auto p = v.begin(); // .begin() is non constant 

now if I write cp=p the compiler doesn’t mark as error, but if I write p=cp the compiler marks the error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

cbegin is a pointer to something that is constant. You can change that pointer to point to something of the same constant type.

You’re confusing this with a pointer, which is constant, to something that is not.

This is hard to see here, but the difference is between

const int* cp; // pointer to a constant value, but can point to something else
int* const pc; // pointer is constant, value can change
const int* const cpc; // pointer cannot be changed, value it points to cannot be changed

You can never make a "pointer that points to something that’s not const" point at something that is const – because that means that you could change what is const, by derefencing the pointer!

const int value = 5; // can never change value
const int value2 = 10; // can never change value
const int* cp = &value; // our pointer to const int points at a const int
*cp = 6; // error: the value of something const can't be changed
cp = &value2; // fine, because we're pointing at a const int

int* p const = &value; // error: trying to point a pointer to non-const to a const, which would allow us to:
*p = 7; // which should be illegal.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading