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();
}
  1. A. Base
  2. B. Derived
  3. C. Compile-time error: override requires the virtual keyword to be repeated
  4. 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

Exams that ask this topic