ProgrammingHardGATE CS · TCS Digital · Advanced
What is printed? (C++17, assume <iostream> and using namespace std)
What is printed? (C++17, assume <iostream> and using namespace std)
struct B { virtual void f(int x = 1) { cout << "B" << x; } };
struct D : B { void f(int x = 2) override { cout << "D" << x; } };
int main() {
B* p = new D;
p->f();
D d;
d.f();
}- A. B1D2
- B. D2D2
- C. D1D2
- D. D1D1
Correct answer: C. D1D2
The virtual call dispatches on the dynamic type (D::f runs), but default arguments are bound at compile time from the static type: through B* the default is 1, through D the default is 2.
More OOP with C++ and Java questions
- 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() {…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct C { int v = 0; C& operator++() { ++v; return this; } C…