ProgrammingVery hardGATE CS · TCS NQT
What does this C++ program print? struct B { B() { f(); } virtual void f() { std::cout << "B"; } }; struct D : B { D() { f(); } void f() override { std::cout << "D"; } }; int main() { D d; B& r = d; r.f(); }
- A. BDD
- B. DDD
- C. BBD
- D. DBD
Correct answer: A. BDD
While B's constructor runs, the object's dynamic type is B, so the virtual call in it reaches B::f and prints B. D's constructor then calls D::f (D), and the call through the reference r dispatches virtually to D::f (D).
More OOP with C++ and Java questions
- 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)…
- 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>…