ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
struct Shape {
    virtual double area() const = 0;
    void report() const { std::cout << "Area: " << area(); }
};
struct Square : Shape {
    double side;
    Square(double s) : side(s) {}
    double area() const override { return side * side; }
};
int main() {
    Square s(4);
    s.report();
}
  1. A. Compilation error: cannot call pure virtual area() from report()
  2. B. Area: 16
  3. C. Area: 0
  4. D. Area: 4

Correct answer: B. Area: 16

report() is a non-virtual member calling the virtual area() on *this; by the time report() runs on a fully constructed Square object, dynamic dispatch correctly resolves to Square::area() = 4*4 = 16. Pure virtual functions CAN be called polymorphically once the derived override exists and the object is fully constructed — they just can't have a body called purely through the base's own default (unless explicitly defined).

More OOP with C++ and Java questions

Exams that ask this topic