ProgrammingHardInfosys · HCL

What is printed? (C++, assume <iostream> and using namespace std)

What is printed? (C++, assume <iostream> and using namespace std)
struct B { virtual void f() { cout << "B"; } };
struct D : B { void f() override { cout << "D"; } };
void show(B b) { b.f(); }
int main() { D d; show(d); }
  1. A. D
  2. B. BD
  3. C. Compile error
  4. D. B

Correct answer: D. B

show takes B by value, so d is sliced into a plain B; no pointer or reference is involved, so f dispatches to B::f.

More OOP with C++ and Java questions

Exams that ask this topic