ProgrammingVery hardMicrosoft/Google SDE MCQ · GATE CS

What is printed?

What is printed?
struct B {
    B() { cout << "B"; }
    B(const B&) { cout << "c"; }
};
struct D : B {
    D() { cout << "D"; }
    D(const D&) { cout << "k"; }
};
int main() {
    D x;
    D y = x;
}
  1. A. BDck
  2. B. BDBk
  3. C. BDk
  4. D. BDcD

Correct answer: B. BDBk

A user-written copy constructor that does not mention the base in its initializer list default-constructs the base, so copying y prints B (not c) and then k. Writing D(const D& o) : B(o) would copy the base.

More OOP with C++ and Java questions

Exams that ask this topic