3

I'm getting confused about the const qualifier. I found and read a lot of article and similar questions such as http://www.cprogramming.com/reference/pointers/const_pointers.html.

What is not clear to me is why g++ complain about this class member:

const string& const name;

but it doesn't complain about

string& const name;

My idea is to declare a constant pointer to a constant string value. I'm using & instead of * to avoid NULL pointers.

What am I missing?

The compiler error is the following:

‘const’ qualifiers cannot be applied to ‘const string& {aka const std::__cxx11::basic_string<char>&}’
  const string& const name;
                      ^
songyuanyao
  • 169,198
  • 16
  • 310
  • 405

1 Answers1

6

string& const name; should fail too. References and pointers are different things.

Reference couldn't be const itself, it doesn't make sense. Unlike pointer, reference could not be bound again after initialized.

Failed demo with gcc and clang.

And see What are the differences between a pointer variable and a reference variable in C++?

Community
  • 1
  • 1
songyuanyao
  • 169,198
  • 16
  • 310
  • 405