ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
struct Shape {
    virtual ~Shape() = default;
    virtual double area() const { return 0; }
};
struct Circle : Shape {
    double r;
    Circle(double r) : r(r) {}
    double area() const override { return 3.14 * r * r; }
};
void report(const Shape &s) {
    cout << s.area();
}
int main() {
    Circle c(2);
    const Shape &ref = c;
    report(ref);
}
  1. A. 0
  2. B. 12.56
  3. C. Compile-time error: area() is const but Circle::area modifies r
  4. D. Undefined behaviour: binding a const Circle reference to a non-const Shape

Correct answer: B. 12.56

Binding a reference to a base type from a derived object (not slicing, since this is a reference, not pass-by-value) preserves the object's identity and vtable. report() takes a const Shape&, and s.area() dispatches virtually to Circle::area(), computing 3.14 * 2 * 2 = 12.56.

More OOP with C++ and Java questions

Exams that ask this topic