Hard
Decorator chain invoked through base and derived pointers
What does this program print?
main.cpp
struct Coffee {
virtual std::string describe(int sugars = 0) const {
return "Coffee(" + std::to_string(sugars) + ")";
}
virtual ~Coffee() = default;
};
struct CoffeeDecorator : Coffee {
explicit CoffeeDecorator(std::unique_ptr<Coffee> inner)
: inner_(std::move(inner)) {}
protected:
std::unique_ptr<Coffee> inner_;
};
struct WithMilk : CoffeeDecorator {
using CoffeeDecorator::CoffeeDecorator;
std::string describe(int sugars = 2) const override {
return inner_->describe(sugars) + " + Milk";
}
};
int main() {
std::unique_ptr<Coffee> drink =
std::make_unique<WithMilk>(std::make_unique<Coffee>());
WithMilk* milky = static_cast<WithMilk*>(drink.get());
std::cout << drink->describe() << "\n";
std::cout << milky->describe() << "\n";
}14 of 44 in Design Patterns