ProgrammingVery hardGATE CS · TCS NQT
What does this C++ program print? struct B { virtual void f(int x = 1) { std::cout << "B" << x; } }; struct D : B { void f(int x = 2) override { std::cout << "D" << x; } }; int main() { B* p = new D; p->f(); }
- A. D2
- B. B1
- C. B2
- D. D1
Correct answer: D. D1
Which function body runs is decided at run time by the dynamic type (D::f), but default arguments are bound at compile time from the static type B*, so x = 1. The output is D1, a mix that surprises most students.
More OOP with C++ and Java questions
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct B { virtual void f(int x = 1) { cout << "B" << x; } }…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout <<…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct T { T() { cout << "T"; } ~T() { cout << "~"; } }; void g()…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct R { const char n; R(const char s) : n(s) { cout << "+" <<…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp template <class T> void f(T) { cout << "T"; } template <class T>…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct V { V() { cout << "V"; } }; struct A : virtual V { A() {…