ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
struct Base {
virtual void f() { cout << "B"; }
};
struct Mid : Base {
};
struct Leaf : Mid {
void f() override { cout << "L"; }
};
int main() {
Mid *p = new Leaf();
p->f();
}- A. B
- B. L
- C. Compile-time error: Mid does not declare f()
- D. Compile-time error: Leaf::f does not override anything in Mid
Correct answer: B. L
Leaf::f() overrides Base::f() directly through the inheritance chain (Mid simply passes the virtual function through unchanged). p is declared as Mid* but points at a Leaf object; virtual dispatch finds the most-derived override in the real object's vtable, Leaf::f, printing L.
More OOP with C++ and Java questions
- What is printed? java public class Main { static class Base { public String toString() { return "Base"; } public boolean equals(Object o)…
- What is printed? cpp template <typename T> T maxVal(T a, T b) { return a > b ? a : b; } int main() { cout << maxVal(3, 7) << " " <<…
- What happens? java interface A { default String id() { return "A"; } } interface B { default String id() { return "B"; } } class D…
- What is printed? cpp struct Base { virtual void f() = 0; void greet() { cout << "greet "; f(); } }; struct Derived : Base { void f()…
- What happens? cpp struct Shape { virtual double area() const = 0; }; int main() { Shape s; cout << s.area(); }
- What is printed? java abstract class Vehicle { abstract void move(); void start() { System.out.print("starting "); move(); } } // in main…