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; }
};- A. It compiles; c becomes 1 and r refers to x
- B. It compiles but r is a dangling reference
- C. Compile-time error only for r
- 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
- Which line fails to compile? cpp struct A { A(int) { } }; struct B { B(A) { } }; void f(B) { } int main() { f(A(1)); // L1 f(1); // L2 }
- In C++, a destructor throws an exception while the stack is already being unwound because of another exception. What happens?
- What happens in C++11 or later? cpp struct T { ~T() { throw 1; } }; int main() { try { T t; } catch (int) { cout << "caught"; } }
- What is printed? cpp struct B { virtual string who() const { return "B"; } }; struct D : B { string who() const override { return "D"; }…
- What is printed? cpp struct G { G() { cout << "G"; } ~G() { cout << "g"; } }; G g1; int main() { cout << "M"; static G s; cout << "m"; }
- Which lines fail to compile? cpp struct P { P(int) { } }; int main() { P a[3]; // L1 P b[2] = {1, 2}; // L2 vector<P> v(3); // L3…