Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this compile? Expecting "cannot assign a constant to a non-const reference"

Tags:

The interviewer showed me a code like this and asked me whether it would compile, and give my reasoning. I told him very certainly that it will not compile, because 10 is a constant and you cannot assign a constant to a non-const reference (like int& b = 10 will not compile), also, _a is a temporary variable and it is also considered const, again, you cannot use non-const reference to refer a const variable.

However, after I came home to my surprise I found it compile perfectly with all possible compilers. Also, I didn't get the job. What part of my understanding went wrong?

class A {     int& a; public:     A(int _a):a(_a) {} };  int main() {     A a(10); }     
like image 686
John Yang Avatar asked Nov 02 '11 04:11

John Yang


People also ask

Why can't you make a non const reference to a literal?

A non-const reference cannot point to a literal. You cannot bind a literal to a reference to non-const (because modifying the value of a literal is not an operation that makes sense) and only l-values can be bound to references to non-const.

Can a const reference be bound to a non const object?

No. A reference is simply an alias for an existing object. const is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r .

What is non const reference?

I think this means that making a reference a "const" when it is referenced to a non const object does absolutely nothing. We may as well take that const keyword out when defining that reference. Not true. You may not modify the a non- const object through a const reference.


1 Answers

there is no "assignment" of a const with this code...

The code calls the constructor which takes an int and in turn calls the initializer of the int& . You skipped several steps the compiler sees/takes when you assumed it meant int& b = 10 while it is more like _a = 10; int& a = _a;. it compiles but is cerainly nothing you would want to use (binding a reference to stack which later on will lead to undefined behaviour/corruption)...

like image 94
Yahia Avatar answered Oct 13 '22 12:10

Yahia