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;
}
  1. A. Compilation error: cannot instantiate pure virtual class Shape
  2. B. 13
  3. C. 9
  4. 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

Exams that ask this topic