Friday, February 24, 2023

Pointer to Implementation (PIMPL) idiom


The Pointer to Implementation (PIMPL) idiom is a technique used in C++ to separate the implementation details of a class from its public interface. 

It is used to reduce the compilation dependencies of a class, improve encapsulation, and hide implementation details from the users of the class.

The PIMPL idiom is implemented by creating a private member of the class that is a pointer to an opaque implementation class. The implementation class is defined in the implementation file, and the public class has a public interface that uses the implementation class through the private pointer.

Here's an example of how you might use the PIMPL idiom to implement a simple class:



    // MyClass.h
    class MyClass
    {
    public:
        MyClass();
        ~MyClass();
        void doSomething();

    private:
        class MyClassImpl;
        MyClassImpl* impl;
    };    

    // MyClass.cpp
    class MyClass::MyClassImpl 
    {
        // implementation details go here
    };

    MyClass::MyClass() : impl(new MyClassImpl) {}
    MyClass::~MyClass() { delete impl; }
    void MyClass::doSomething() { /* use impl to do something */ }


In this example, the MyClass class has a private member impl that is a pointer to an implementation class called MyClassImpl. The implementation details of MyClass are hidden from the users of the class, reducing compilation dependencies and improving encapsulation.
It's worth noting that C++11 introduced the std::unique_ptr which can be used to manage the memory of the implementation class and avoid the need to explicitly call the destructor of the implementation class.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...