Basic Visitor in C++

The only way to really understand how the Visitor pattern operates is to work through an example. Let's start with a very simple one. First, we need a class hierarchy:

class Pet {    public:    virtual ~Pet() {}    Pet(const std::string& color) : color_(color) {}    const std::string& color() const { return color_; }    private:    std::string color_;};class Cat : public Pet {    public:    Cat(const std::string& color) : Pet(color) {}};class Dog : public Pet {    public:    Dog(const std::string& color) : Pet(color) {}};

In this hierarchy, we have the Pet base class and several derived classes for different pet animals. Now we want to add some operations to our classes, such as feed the pet or play with the pet. The implementation depends on the ...

Get Hands-On Design Patterns with C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.