ProgrammingVery hardMicrosoft/Google SDE MCQ · GATE CS

What happens?

What happens?
class Shape {
public:
    virtual double area() const = 0;
};
class Square : public Shape {
    double s = 2;
    double area() const override { return s * s; }   // private in Square
};
int main() {
    Square q;
    Shape& r = q;
    cout << r.area();
}
  1. A. Compile error: area() is private in Square
  2. B. Compile error: Square is still abstract
  3. C. It prints 4
  4. D. It throws at run time because access is violated

Correct answer: C. It prints 4

Access is checked against the static type used in the call: Shape::area is public, so r.area() is allowed, and virtual dispatch then runs Square's override even though it is private there. Calling q.area() directly would not compile.

More OOP with C++ and Java questions

Exams that ask this topic