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;
}
  1. A. 34
  2. B. 32
  3. C. 12
  4. 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

Exams that ask this topic