ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
struct Shape {
virtual double area() const = 0;
virtual ~Shape() = default;
};
struct Square : Shape {
double s;
Square(double s) : s(s) {}
double area() const override { return s * s; }
};
int main() {
Shape *shapes[2] = { new Square(2), new Square(3) };
double total = 0;
for (auto *sh : shapes) total += sh->area();
cout << total;
}- A. Compilation error: cannot instantiate pure virtual class Shape
- B. 13
- C. 9
- D. 4
Correct answer: B. 13
Shape itself is abstract (pure virtual area()) and can never be instantiated directly, but Square overrides area() and is a concrete type, so creating Square objects and storing pointers in a Shape* array is fine; virtual dispatch sums 2*2 + 3*3 = 4 + 9 = 13.
More OOP with C++ and Java questions
- 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…
- What is printed? java interface Greeter { String greet(); } class Main { public static void main(String[] args) { Greeter g = () -> "hi…
- What is printed? cpp struct Resource { virtual ~Resource() { cout << "~Resource "; } }; struct FileResource : Resource { ~FileResource() {…