ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
struct Shape {
    virtual double area() const = 0;
    bool operator<(const Shape &o) const { return area() < o.area(); }
};
struct Circle : Shape {
    double r;
    Circle(double r) : r(r) {}
    double area() const override { return 3.14 * r * r; }
};
int main() {
    Circle a(1), b(2);
    cout << (a < b);
}
  1. A. 0
  2. B. 1
  3. C. Compile-time error: operator< cannot call a pure virtual function
  4. D. Undefined behaviour

Correct answer: B. 1

operator< is a concrete member of the abstract Shape, and it may freely call the pure virtual area(); for actual Circle objects this dispatches to Circle::area(). a's area (3.14) is less than b's area (12.56), so a < b evaluates true, printed as 1.

More OOP with C++ and Java questions

Exams that ask this topic