ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
struct B {
virtual void f() = 0;
};
void B::f() { cout << "B"; }
struct D : B {
void f() override { cout << "D"; B::f(); }
};
int main() {
D d;
B& r = d;
r.f();
r.B::f();
}- A. DB
- B. DBD
- C. It does not compile: a pure virtual function cannot have a body
- D. DBB
Correct answer: D. DBB
A pure virtual function may still be defined; B stays abstract, but derived classes can call the definition explicitly. r.f() dispatches to D::f, which prints D and then calls B::f (B). r.B::f() is a qualified call, which suppresses virtual dispatch and calls B's definition directly (B).
More OOP with C++ and Java questions
- What is printed? cpp struct C { static int n; C() { n++; } ~C() { n--; } }; int C::n = 0; void f(C c) { } int main() { C a; f(a); f(a); {…
- What is printed? cpp struct S { void f() { cout << "N"; } void f() const { cout << "C"; } }; void call(const S& s) { s.f(); } int main() {…
- What is printed? cpp struct B { void f(int) { cout << "Bi "; } void f(double) { cout << "Bd "; } }; struct D : B { using B::f; void f(int)…
- What happens with this code? cpp class B { public: virtual void f() { cout << "B"; } }; class D : public B { private: void f() override {…
- What is printed? cpp struct B { virtual const char who() const { return "B"; } }; struct D : B { const char who() const override { return…
- What is printed? cpp struct A { int v = 0; A() { cout << "A"; } }; struct B : A { B() { cout << "B"; } }; struct C : A { C() { cout <<…