ProgrammingVery hardMicrosoft/Amazon SDE MCQ · GATE CS
What is printed?
What is printed?
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() {
D d;
B& b = d;
b.f();
d.f();
}- A. D2D2
- B. B1D2
- C. D1D1
- D. D1D2
Correct answer: D. D1D2
The function body is chosen at run time (D::f both times), but default arguments come from the static type of the expression: B& gives 1, D gives 2.
More OOP with C++ and Java questions
- What is printed? cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout << "Bd"; } }; struct D : B { void f(double) { cout <<…
- What is printed? cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout << "Bd"; } }; struct D : B { using B::f; void…
- What is printed? cpp struct B { virtual char id() const { return 'B'; } }; struct D : B { char id() const override { return 'D'; } }; void…
- What is printed when compiled as C++17? cpp struct T { T() { cout << "c"; } T(const T&) { cout << "k"; } }; T make() { return T(); } int…
- What is printed? cpp struct C { static int n; C() { ++n; } C(const C&) { ++n; } ~C() { --n; } }; int C::n = 0; void f(C c) { cout << C::n…
- What is printed? cpp struct N { int v; N& operator++() { v += 10; return this; } N operator++(int) { N t = this; v += 1; return t; } }…