Easy
Copying a Composite menu tree
What happens when this program is built and run?
main.cpp
struct Component {
virtual ~Component() = default;
virtual void print() const = 0;
};
struct Leaf : Component {
std::string name;
explicit Leaf(std::string n) : name(std::move(n)) {}
void print() const override { std::cout << name << "\n"; }
};
struct Menu : Component {
std::vector<std::unique_ptr<Component>> children;
void add(std::unique_ptr<Component> c) { children.push_back(std::move(c)); }
void print() const override {
for (const auto& c : children) c->print();
}
};
int main() {
Menu file;
file.add(std::make_unique<Leaf>("Open"));
file.add(std::make_unique<Leaf>("Save"));
Menu recent = file; // start from a copy of "file"
recent.add(std::make_unique<Leaf>("report.txt"));
recent.print();
}29 of 44 in Design Patterns