ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
struct Base {
    Base() { cout << "Base "; }
    Base(const Base&) { cout << "BaseCopy "; }
};
struct Derived : Base {
    Derived() { cout << "Derived "; }
    Derived(const Derived &other) : Base(other) { cout << "DerivedCopy "; }
};
int main() {
    Derived d1;
    Derived d2 = d1;
}
  1. A. Base Derived BaseCopy DerivedCopy
  2. B. Base Derived Base DerivedCopy
  3. C. Base Derived BaseCopy Derived
  4. D. Base Derived DerivedCopy BaseCopy

Correct answer: A. Base Derived BaseCopy DerivedCopy

d1's construction runs Base() then Derived() (Base Derived). d2's copy-construction explicitly passes other to Base's copy constructor (Base(other) in the initializer list), running BaseCopy, and then Derived's own copy-constructor body runs, printing DerivedCopy.

More OOP with C++ and Java questions

Exams that ask this topic