ProgrammingHardProduct-company placement · C++

What is printed?

What is printed?
struct B {
    void run() { step(); }
    virtual void step() { cout << "B"; }
};
struct D : B { void step() override { cout << "D"; } };
int main() {
    D d;
    d.run();
    B b = d;
    b.run();
}
  1. A. DD
  2. B. DB
  3. C. BB
  4. D. BD

Correct answer: B. DB

Inside the non-virtual run(), step() is still a virtual call on *this, so for d it reaches D::step. b is a sliced copy whose dynamic type is B, so it calls B::step.

More OOP with C++ and Java questions

Exams that ask this topic