ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
struct Shape {
    virtual double area() const { return 0; }
    virtual void print() const { cout << "Area: " << area(); }
};
struct Square : Shape {
    double side;
    Square(double s) : side(s) {}
    double area() const override { return side * side; }
};
int main() {
    Shape *s = new Square(3);
    s->print();
}
  1. A. Area: 0
  2. B. Area: 9
  3. C. Compile-time error: print() cannot call area() before Square is fully built
  4. D. Undefined behaviour

Correct answer: B. Area: 9

By the time main calls s->print(), the Square object is already fully constructed, so this is an ordinary (not constructor-time) virtual call. print() calls area() virtually, which dispatches to Square::area(), returning 3*3 = 9, giving "Area: 9".

More OOP with C++ and Java questions

Exams that ask this topic