ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
struct Base {
virtual void f() { cout << "Base"; }
};
struct Derived : Base {
void f() { cout << "Derived"; }
};
int main() {
Base *p = new Derived();
p->f();
}- A. Base
- B. Derived
- C. Compile-time error: override requires the virtual keyword to be repeated
- D. Undefined behaviour: virtual is not inherited
Correct answer: B. Derived
Once a function is declared virtual in a base class, it remains virtual in every derived class automatically; repeating the virtual keyword (or writing override) is optional style, not a requirement. Derived::f matches Base::f's signature exactly, so it overrides it and the virtual call through Base* dispatches to Derived::f.
More OOP with C++ and Java questions
- What is printed? java class Picker { static void f(int a, int b) { System.out.print("fixed"); } static void f(int... a) {…
- What happens when this is compiled? cpp struct Base final { virtual void f() { cout << "Base"; } }; struct Derived : Base { };
- What is printed? cpp struct Base {}; struct Derived : Base {}; void f(Base b) { cout << "Base"; } void f(Derived d) { cout << "Derived"; }…
- What is printed? cpp struct Shape { virtual double area() const = 0; virtual ~Shape() = default; }; struct Square : Shape { double s…
- What is printed? java abstract class Shape { abstract double area(); public String toString() { return "Shape(area=" + area() + ")"; } }…
- What is printed? java class Vehicle { void start() { System.out.print("Vehicle-start "); honk(); } void honk() { System.out.print("beep")…