ProgrammingHardHCL · Tech Mahindra pattern
What happens when this is compiled?
What happens when this is compiled?
struct Base final {
virtual void f() { cout << "Base"; }
};
struct Derived : Base {
};- A. Compiles; Derived simply cannot override f()
- B. Compile-time error: Base is declared final, so no class may derive from it
- C. Compiles, but Derived has no constructor
- D. Compile-time error: a final class cannot have virtual functions
Correct answer: B. Compile-time error: Base is declared final, so no class may derive from it
Applying final to a class (as opposed to a member function) forbids any class from inheriting from it at all. struct Derived : Base is rejected at compile time regardless of what Derived would do with f().
More OOP with C++ and Java questions
- 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")…
- What is printed? cpp struct Base { virtual void f() const { cout << "Base "; } }; struct Derived : Base { void f() const override { cout…
- What is printed? cpp struct Base { virtual Base clone() const { cout << "Base::clone "; return new Base(this); } }; struct Derived : Base…