What are design patterns commonly used in C++?
Why Interviewers Ask This
Mid-level C++ roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.
Answer
Key design patterns implemented idiomatically in C++: 1. Singleton: one instance only. C++11 magic statics make this thread-safe: class Logger { static Logger& instance() { static Logger log; return log; } Logger() = default; public: static Logger& get() { return instance(); } void log(std::string msg) { std::cout << msg; } }; Logger::get().log("hello");. 2. Factory Method: create objects without specifying exact class: class ShapeFactory { public: static std::unique_ptr<Shape> create(std::string type) { if (type == "circle") return std::make_unique<Circle>(); if (type == "square") return std::make_unique<Square>(); throw std::invalid_argument("Unknown shape"); } };. 3. Observer: notify multiple subscribers of changes: class EventEmitter { std::vector<std::function<void(int)>> listeners; public: void subscribe(std::function<void(int)> listener) { listeners.push_back(listener); } void emit(int event) { for (auto& l : listeners) l(event); } };. 4. CRTP (Curiously Recurring Template Pattern) — static polymorphism: template<typename Derived> class Base { void interface() { static_cast<Derived*>(this)->implementation(); } }; class Derived : public Base<Derived> { void implementation() { /* ... */ } };. No vtable overhead — compile-time dispatch. 5. RAII + Policy-based design: inject behavior through templates (Policy classes) for maximum flexibility without runtime overhead. 6. Type Erasure (std::any, std::variant, std::function): store heterogeneous types without inheritance.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.
Previous
What are function pointers and std::function in C++?
Next
What is undefined behavior in C++ and how do you avoid it?