ProgrammingHardProduct-company placement · C++

What happens when this is compiled?

What happens when this is compiled?
struct K {
    const int c;
    int& r;
    K(int& x) { c = 1; r = x; }
};
  1. A. It compiles; c becomes 1 and r refers to x
  2. B. It compiles but r is a dangling reference
  3. C. Compile-time error only for r
  4. D. Compile-time error: c and r must be initialised in the member initializer list

Correct answer: D. Compile-time error: c and r must be initialised in the member initializer list

By the time the constructor body runs, members are already initialised; a const member and a reference member cannot be left uninitialised or assigned later. Write K(int& x) : c(1), r(x) { }.

More OOP with C++ and Java questions

Exams that ask this topic