ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
class Base {
public:
    Base() { hello(); }
    virtual void hello() { cout << "B"; }
};
class Derived : public Base {
public:
    Derived() { hello(); }
    void hello() override { cout << "D"; }
};
int main() { Derived d; }
  1. A. D
  2. B. DD
  3. C. BD
  4. D. BB

Correct answer: C. BD

While Base's constructor runs, the object is still a Base, so virtual calls resolve to Base::hello (B). In Derived's constructor the dynamic type is Derived (D). Java behaves differently: it would dispatch to the derived override even from the base constructor.

More OOP with C++ and Java questions

Exams that ask this topic