ProgrammingVery hardTCS NQT Prime · Infosys SP

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

What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std)
struct A { virtual void f(int x = 1) { cout << "A" << x; } };
struct B : A { void f(int x = 2) override { cout << "B" << x; } };
int main() { A* p = new B; p->f(); }
  1. A. B1
  2. B. B2
  3. C. A1
  4. D. A2

Correct answer: A. B1

Virtual dispatch picks B::f at run time, but default arguments are bound statically from the type of the pointer (A*), so x = 1.

More OOP with C++ and Java questions

Exams that ask this topic