Table of Contents

C++ Pimpl

Pimpl (Pointer to Implementation) is a design pattern that hides implementation details behind a pointer, reducing compilation dependencies and enabling binary compatibility across library versions. The public header declares only the interface; the actual implementation lives in a separate private class.

Use Pimpl to decouple the public API from implementation details and reduce header file bloat.

Example

This example shows how Pimpl separates interface from implementation to minimize compilation dependencies.

// compile: g++ -o pimpl pimpl.cpp
// run: ./pimpl
// description: Pimpl pattern decouples interface from implementation
 
#include <iostream>
#include <memory>
 
class Widget {
public:
    Widget();
    ~Widget();
    void draw();
private:
    class Impl;
    std::unique_ptr<Impl> pimpl;
};
 
class Widget::Impl {
public:
    void draw() { std::cout << "Drawing widget\n"; }
};
 
Widget::Widget() : pimpl(std::make_unique<Impl>()) {}
Widget::~Widget() = default;
 
void Widget::draw() { pimpl->draw(); }
 
int main() {
    Widget w;
    w.draw();
    return 0;
}