How do I implement pImpl (pointer to implementation) in C++?

The pImpl (pointer to implementation) idiom is a popular design pattern in C++ used to encapsulate implementation details and reduce compile-time dependencies. It allows for a separation between the interface and implementation which can be beneficial for hiding complex implementations and enhancing build times.

Keywords: C++, pImpl, pointer to implementation, design pattern, encapsulation, implementation details.
Description: This article explains the pImpl idiom in C++ and provides an example of its implementation, focusing on its benefits such as reduced compile-time dependencies.
#include <iostream>

// Forward declaration of the implementation class
class WidgetImpl;

// Interface class
class Widget {
public:
    Widget();
    ~Widget();
    
    void doSomething();

private:
    WidgetImpl* pImpl; // Pointer to implementation
};

// Implementation class
class WidgetImpl {
public:
    void doSomething() {
        std::cout << "Doing something!" << std::endl;
    }
};

// Constructor: allocate the implementation
Widget::Widget() : pImpl(new WidgetImpl) {}

// Destructor: clean up the implementation
Widget::~Widget() {
    delete pImpl;
}

// Forwarding function to implementation
void Widget::doSomething() {
    pImpl->doSomething();
}

int main() {
    Widget widget;
    widget.doSomething();
    return 0;
}
    

Keywords: C++ pImpl pointer to implementation design pattern encapsulation implementation details.