ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
struct Base {
virtual void f() = 0;
void greet() { cout << "greet "; f(); }
};
struct Derived : Base {
void f() override { cout << "Derived::f"; }
};
int main() {
Derived d;
d.greet();
}- A. Compilation error: cannot call pure virtual f() from greet()
- B. greet Derived::f
- C. greet
- D. Compilation error: Base is abstract so greet() cannot be called
Correct answer: B. greet Derived::f
Base is abstract only because it has a pure virtual f(); non-pure methods like greet() are perfectly callable once a concrete derived type exists. Calling the pure virtual f() from within a non-constructor/destructor context dispatches normally via vtable to Derived::f, so output is "greet Derived::f".
More OOP with C++ and Java questions
- 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…
- What is printed? cpp class Base { public: Base(int x) { cout << "Base(" << x << ") "; } }; class Derived : public Base { public: Derived()…
- What is printed? java class Outer { static class Nested { void show() { System.out.print("Nested.show"); } } } // in main: Outer.Nested n…
- What is printed? java interface Shape { double area(); static Shape unitSquare() { return () -> 1.0; } } // in main: Shape s =…
- What is printed? java class Shape { protected String name = "Shape"; Shape() { System.out.print(name + " "); } } class Circle extends…