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); }
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.
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 .
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.
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)...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With