Medium
Abstract Factory override returning a derived unique_ptr
What happens when this program is built and run?
main.cpp
struct Button {
virtual ~Button() = default;
virtual void paint() const = 0;
};
struct MacButton : Button {
void paint() const override { std::cout << "mac button\n"; }
};
struct WidgetFactory {
virtual ~WidgetFactory() = default;
virtual std::unique_ptr<Button> createButton() const = 0;
};
struct MacFactory : WidgetFactory {
// more specific return type, so code holding a MacFactory gets a MacButton
std::unique_ptr<MacButton> createButton() const override {
return std::make_unique<MacButton>();
}
};
int main() {
std::unique_ptr<WidgetFactory> f = std::make_unique<MacFactory>();
f->createButton()->paint();
}30 of 44 in Design Patterns