ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
struct A { virtual void f() { cout << "A"; } };
struct B : A { void f() override { cout << "B"; A::f(); } };
int main() {
A *p = new B();
p->f();
}- A. B
- B. A
- C. BA
- D. AB
Correct answer: C. BA
p->f() dispatches virtually to B::f(), which first prints B, then explicitly calls A::f() by name (a statically bound call that bypasses virtual dispatch), printing A. Result: BA.
More OOP with C++ and Java questions
- What is printed? java class Vehicle { int wheels() { return 4; } } class Motorcycle extends Vehicle { @Override int wheels() { return 2; }…
- What is printed? cpp struct Base { virtual Base clone() const { cout << "Base::clone "; return new Base(this); } }; struct Derived : Base…
- What is printed? java interface Greeter { default String hello() { return "Hi"; } } class Formal implements Greeter { @Override public…
- What is printed? cpp struct Base { Base() { cout << "Base-ctor "; } ~Base() { cout << "Base-dtor "; } }; struct Derived : Base { Derived()…
- What is printed? java public class Main { static int risky() { try { return 1; } finally { return 2; } } public static void main(String[]…
- What is printed? java class MyChecked extends Exception { MyChecked(String m) { super(m); } } public class Main { static void risky()…