Medium
Adding a new type to a classic Visitor hierarchy
A new shape, Triangle, is added to the hierarchy and its accept() is implemented, but the author forgets to add a visit(Triangle&) overload to AreaVisitor. What happens?
main.cpp
struct Circle; struct Square; struct Triangle;
struct ShapeVisitor {
virtual void visit(Circle&) = 0;
virtual void visit(Square&) = 0;
// no visit(Triangle&) added
virtual ~ShapeVisitor() = default;
};
struct Shape { virtual void accept(ShapeVisitor&) = 0; virtual ~Shape() = default; };
struct Circle : Shape { void accept(ShapeVisitor& v) override { v.visit(*this); } };
struct Square : Shape { void accept(ShapeVisitor& v) override { v.visit(*this); } };
struct Triangle : Shape { void accept(ShapeVisitor& v) override { v.visit(*this); } };
struct AreaVisitor : ShapeVisitor {
void visit(Circle&) override { std::cout << "circle area\n"; }
void visit(Square&) override { std::cout << "square area\n"; }
};
int main() {
AreaVisitor av;
Triangle t;
t.accept(av);
}15 of 44 in Design Patterns