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();
}- A. It compiles and prints "DD"
- B. Compile-time error: cannot declare a variable of abstract class type Base
- C. It compiles, but b.f() would throw at runtime if called
- 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
- What happens when this is compiled? cpp struct A { int x; }; struct B : A {}; struct C : A {}; struct D : B, C {}; int main() { D d; d.x =…
- What is printed? cpp struct Base { virtual ~Base() {} }; struct Derived : Base {}; struct Other : Base {}; int main() { Base b = new…
- What is printed? java class Animal { void speak() { System.out.print(".."); } } class Dog extends Animal { void speak() {…
- What is printed? cpp struct Base { public: virtual ~Base() { cout << "~Base "; } }; struct Derived : Base { int data = new int[10]…
- What is printed? cpp struct Vehicle { virtual string type() { return "Vehicle"; } }; struct Car : Vehicle { string type() override {…
- What is printed? java abstract class Shape { abstract double area(); String describe() { return "Area=" + area(); } } class Square extends…