ProgrammingHardMicrosoft/Google SDE MCQ · GATE CS
What is printed?
What is printed?
struct A { virtual void f() = 0; };
void A::f() { cout << "A"; }
struct B : A { void f() override { A::f(); cout << "B"; } };
int main() {
B b;
A& r = b;
r.f();
}- A. B
- B. Compile error: a pure virtual function cannot have a body
- C. AB
- D. BA
Correct answer: C. AB
A pure virtual function may still be defined; it keeps A abstract, but a derived class can call it explicitly with A::f(). r.f() dispatches to B::f, which prints A and then B.
More OOP with C++ and Java questions
- What is printed? cpp struct B { virtual ~B() { } }; struct D1 : B { }; struct D2 : B { }; int main() { B p = new D1; cout <<…
- What is printed? cpp struct B { }; // no virtual functions struct D : B { }; struct VB { virtual ~VB() { } }; struct VD : VB { }; int…
- What is printed (C++17)? cpp int main() { int x = 0; auto f = [x]() mutable { return ++x; }; f(); auto g = f; f(); cout << f() << g() <<…
- What is printed? cpp struct B { }; struct D : B { }; void f(B&) { cout << "B"; } void f(D&) { cout << "D"; } int main() { D d; B& b = d…
- What is printed? cpp struct T { int id; T(int i) : id(i) { cout << "+" << id; } ~T() { cout << "-" << id; } }; T g(1); void f() { static T…
- What is printed? cpp int main() { int a = 1, b = 2; int& r = a; r = b; r = 5; cout << a << b; }