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);
}
there is no “assignment” of a const with this code…
The code calls the constructor which takes an
intand in turn calls the initializer of theint&. You skipped several steps the compiler sees/takes when you assumed it meantint& b = 10while 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)…