Learning Hub Search Ctrl K

Legacy C++ › 7. Idioms and Patterns

The Pimpl Idiom

Hide implementation details and cut compile-time dependencies.

advanced #pimpl#idiom#compilation-firewall#encapsulation#opaque-pointer

Explanation

Pimpl (“pointer to implementation”, also the compilation firewall or Cheshire Cat) hides a class’s private members behind a forward-declared Impl struct and one owning pointer. The public header then:

  • contains no private data or helper types, so changing them does not force clients to recompile;
  • needs fewer #includes, speeding builds;
  • keeps a stable binary interface, which is useful for libraries and DLLs (MFC extension DLLs, plug-ins);
  • hides implementation details and third-party headers.

Costs: one extra heap allocation, one pointer indirection per call, and you must write the special member functions yourself (Rule of Three): the destructor must be defined in the .cpp, where Impl is a complete type.

Example

All three pieces are shown in one file for brevity; the comments mark where each would go.

#include <iostream>
#include <string>

// ===== widget.h =====
class Widget {
public:
    explicit Widget(const std::string& name);
    Widget(const Widget& other);
    Widget& operator=(const Widget& other);
    ~Widget();
    void draw() const;
    void rename(const std::string& n);
private:
    struct Impl;                       // declared, not defined
    Impl* impl_;                       // the only data member
};

// ===== widget.cpp =====
struct Widget::Impl {                  // free to change without touching widget.h
    std::string name;
    int         drawCount;
    Impl(const std::string& n) : name(n), drawCount(0) {}
};

Widget::Widget(const std::string& name) : impl_(new Impl(name)) {}
Widget::Widget(const Widget& o) : impl_(new Impl(*o.impl_)) {}
Widget& Widget::operator=(const Widget& o) {
    if (this != &o) {
        Impl* fresh = new Impl(*o.impl_);      // allocate first (exception safety)
        delete impl_;
        impl_ = fresh;
    }
    return *this;
}
Widget::~Widget() { delete impl_; }            // Impl is complete here

void Widget::draw() const {
    std::cout << "drawing " << impl_->name << "\n";
    ++impl_->drawCount;                        // allowed: pointee is not const
}
void Widget::rename(const std::string& n) { impl_->name = n; }

// ===== client =====
int main() {
    Widget w("button");
    Widget copy = w;
    copy.rename("slider");
    w.draw();
    copy.draw();
    return 0;
}

Common pitfalls

  • Defining the destructor inline in the header (or defaulting it) while Impl is incomplete is an error, or UB if using delete.
  • Forgetting the copy constructor/assignment gives a shallow copy and a double delete.
  • A const member function can still modify *impl_, because constness is not deep. Be disciplined.
  • Do not use Pimpl on tiny, hot, value-like classes: the indirection and allocation cost is real.
  • Writing the Impl members as private inner classes still needs the forward declaration in the class.

Legacy vs modern

With C++11, hold the pointer in std::unique_ptr<Impl> (still define the destructor and move operations in the .cpp), or std::shared_ptr<Impl> for cheap shared copies. Modules (C++20) reduce, but do not remove, the need for the idiom.

Exercises

1. Why must ~Widget() be defined in the .cpp file, not in the header?

delete impl_ needs the complete definition of Impl, which is only visible in the .cpp file.