ProgrammingVery hardProduct company OA

What is printed?

What is printed?
class Base {
public:
    Base() { std::cout << "Base() "; }
    virtual void show() { std::cout << "Base::show"; }
};
class Derived : public Base {
public:
    Derived() { std::cout << "Derived() "; }
    void show() override { std::cout << "Derived::show"; }
};
int main() {
    Base *arr[2];
    arr[0] = new Base();
    arr[1] = new Derived();
    for (auto *p : arr) p->show();
}
  1. A. Base::showDerived::show
  2. B. Base() Derived() Base::showDerived::show
  3. C. Base::showBase::show
  4. D. Base() Base() Derived() Base::showDerived::show

Correct answer: D. Base() Base() Derived() Base::showDerived::show

Both objects are fully constructed before the loop runs. arr[0]=new Base() prints "Base() ". arr[1]=new Derived() runs Base's constructor then Derived's: "Base() Derived() ". Only then does the loop call show() virtually on each: the Base object prints Base::show, the Derived object prints Derived::show. Concatenated: Base() Base() Derived() Base::showDerived::show.

More OOP with C++ and Java questions

Exams that ask this topic