ProgrammingHardHCL · Tech Mahindra pattern

What happens when Base b; is added inside main, right before the existing lines?

What happens when `Base b;` is added inside main, right before the existing lines?
struct Base { virtual void f() = 0; };
struct Derived : Base { void f() override { cout << "D"; } };
int main() {
    Base *p = new Derived();
    p->f();
}
  1. A. It compiles and prints "DD"
  2. B. Compile-time error: cannot declare a variable of abstract class type Base
  3. C. It compiles, but b.f() would throw at runtime if called
  4. D. It compiles because Base has a defined vtable entry

Correct answer: B. Compile-time error: cannot declare a variable of abstract class type Base

f() = 0 makes Base an abstract class with a pure virtual function. A class with any pure virtual function cannot be instantiated directly; only classes that override every pure virtual, like Derived, can be. Base *p = new Derived() remains fine since p is just a pointer.

More OOP with C++ and Java questions

Exams that ask this topic