ProgrammingHardProduct-company placement · GATE CS

A drawing program uses the Visitor pattern: Shape has accept(Visitor v), and Circle implements it as v.visit(this). Visitor has overloads visit(Circle) and visit(Square). Why can't client code holding a Shape s simply call v.visit(s)?

  1. A. visit methods must be static, so they need an instance to call them
  2. B. Visitor objects cannot be passed to shapes directly
  3. C. It would work, but accept() makes it faster
  4. D. Overloads are chosen from the static type Shape at compile time, so no visit(Circle) is selected; accept() adds a second, virtual dispatch on the shape's real type

Correct answer: D. Overloads are chosen from the static type Shape at compile time, so no visit(Circle) is selected; accept() adds a second, virtual dispatch on the shape's real type

Java and C++ dispatch virtually only on the receiver. Inside Circle.accept, this has static type Circle, so the right overload is fixed at compile time: two dispatches (on the shape, then on the visitor) give double dispatch. v.visit(s) would need a visit(Shape) overload and lose the type.

More OOP with C++ and Java questions

Exams that ask this topic