ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
struct Base {
    Base() { cout << "Base "; }
    Base(int x) { cout << "Base(" << x << ") "; }
};
struct Derived : Base {
    Derived() : Base(5) { cout << "Derived "; }
    Derived(int x) { cout << "Derived(" << x << ") "; }
};
int main() {
    Derived d1;
    Derived d2(9);
}
  1. A. Base(5) Derived Base Derived(9)
  2. B. Base Derived Base(9) Derived
  3. C. Base(5) Derived Derived(9) Base
  4. D. Base(5) Derived(9) Base Derived

Correct answer: A. Base(5) Derived Base Derived(9)

Derived() explicitly calls Base(5) in its initializer list, printing Base(5), then its own body prints Derived. Derived(int x) has no explicit base-constructor call, so the compiler implicitly inserts a call to Base's default constructor, Base(), printing Base, before Derived(x)'s own body prints Derived(9).

More OOP with C++ and Java questions

Exams that ask this topic