ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Base {
public:
    Base(int x) { cout << "Base(" << x << ") "; }
};
class Derived : public Base {
public:
    Derived() : Base(42) { cout << "Derived() "; }
    Derived(int y) : Base(y) { cout << "Derived(" << y << ") "; }
};
int main() {
    Derived d1;
    Derived d2(7);
}
  1. A. Base(42) Derived() Base(7) Derived(7)
  2. B. Derived() Base(42) Derived(7) Base(7)
  3. C. Base(0) Derived() Base(0) Derived(7)
  4. D. Compilation error: Base has no default constructor

Correct answer: A. Base(42) Derived() Base(7) Derived(7)

Base has no default constructor, so every Derived constructor MUST explicitly initialise it in its member-init list, which both do (Base(42) and Base(y)). Base always runs first for each object: Base(42) then Derived() for d1; Base(7) then Derived(7) for d2.

More OOP with C++ and Java questions

Exams that ask this topic