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(); }- A. B1
- B. B2
- C. A1
- 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
- What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std) cpp struct A { virtual void p() { cout << "A"; }…
- What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std) cpp struct X { string n; X(const char s) : n(s) {…
- What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std) cpp struct A { A() { f(); } virtual void f() {…
- What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std) cpp struct A { virtual ~A() { f(); } virtual void…
- What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std) cpp struct T { T() { cout << "d"; } T(const T&) {…
- What is printed? (no move constructor is declared) (C++17; assume <iostream>, <string>, <vector> and using namespace std) cpp struct T {…