2

I'd like to know what's the difference between const ref and const pointer in c++. When I declare on something to be const ref, can I change it's VALUE? or the const goes on the object? Because I know that const pointer means you cannot change the POINTER but you can change the VALUE it points to.

for example:

const char& a; // ? const char* a; // pointer is const 
2
  • 3
    Re-evaluate what you "know". Test it. Commented May 1, 2012 at 17:34
  • 4
    const char* a; // pointer is const -- No, the referent is const. Commented May 1, 2012 at 17:34

3 Answers 3

5

Fred const& x;

It means x aliases a Fred object, but x can't be used to change that Fred object.

Fred const* p;

Fred const* p means "p points to a constant Fred": the Fred object can't be changed via p.

Fred* const p;

Fred* const p means "p is a const pointer to a Fred": you can't change the pointer p, but you can change the Fred object via p.


It's possible to combine the last to to get:

Fred const* const p;

Fred const* const p means "p is a constant pointer to a constant Fred": you can't change the pointer p itself, nor can you change the Fred object via p.

For more on this visit this link.

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

Comments

2

const char* a; // pointer is const

Wrong, this is a pointer to a constant. This:

char* const a; // pointer is const

is a constant pointer.

1 Comment

While your observation is correct, this doesn't really answer the question.
2

I prefer to write these like this: char const * a vs. char * const a.

This allows you to read from right to left: char const * a is: a is a pointer to a constant char, and char * const a is: a is a constant pointer to a char. And if I read other code, I just remember that const char* a = char const* a.

To answer the other part of your question: When I declare on something to be const ref, can I change it's VALUE? People misuse the term const ref to actually mean reference to a constant (since a constant reference makes no sense). So, const ref const char& a means that you cannot change the value. But if you actually mean you want a constant reference, char& const a then you can change the value and the const part makes no difference.

For pointers, const char* a means you cannot change the value a points to. Compare this to char* const a which means you cannot change the pointer, but you can change the value a points to.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.