ProgrammingVery hardProduct-company placement · C++
What is printed?
What is printed?
struct B { int b; B(int x) : b(x) { } };
struct D : B { int d; D(int x, int y) : B(x), d(y) { } };
int main() {
D d1(1, 2), d2(3, 4);
B& r = d1;
r = d2;
cout << d1.b << d1.d;
}- A. 34
- B. 32
- C. 12
- D. 14
Correct answer: B. 32
r = d2 calls B::operator=, which copies only the B part (b = 3). The D part of d1 is untouched (d stays 2): a 'partial assignment', another form of slicing.
More OOP with C++ and Java questions
- How many of these statements about C++ dynamic memory are correct? (i) Memory obtained with new[] must be released with delete[]. (ii)…
- What happens when this is compiled? cpp struct K { const int c; int& r; K(int& x) { c = 1; r = x; } };
- 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"; }…