4
int main() { int a = 10; const int &b = a; int &c = b; //gives error : C should a reference to a const b auto d = b; // why const is ignored here? d = 15; cout << a << d; } 

In c++ Primer, it's mentioned that "const in reference type is always low-level " Then how come auto d = b is not constant?

3 Answers 3

6

Because the type deduction rules for auto deduce to an object type. You are copy initializing a new int from the one referenced by b.

That's by design. We want to create new objects without explicitly specifying their type. And more often than not, it's a new object that is a copy some other object. Had it deduced to a reference, it would defeat the intended purpose.

If you want the deduced type to be a reference when the initializer is a reference, then that is accomplished with a placeholder of decltype(auto):

decltype(auto) d = b; // d and b now refer to the same object d = 15; // And this will error because the cv-qualifiers are the same as b's 
Sign up to request clarification or add additional context in comments.

Comments

2

For auto d = b, you're declaring d as non-reference. That means d will be a new object copied from b, then the reference part of b will be ignored, after that, the const-ness is ignored too. So the type of d is int.

You can declare d as reference explicitly, then the const-ness of b won't be ignored. e.g.

auto& d = b; // the type of d is const int & 

Comments

0

Because the deducted type is as an int, not an int&.

That means d is not a reference.

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.