Search code examples
c++pimpl-idiom

How to give access to public members with Pimpl?


  • pimpl.h
#include <memory>

class MyClassImpl;

class MyClass {
    void Foo();

    struct MyStruct {
      int a;
      int b;
    } variable_struct;
private:
    std::unique_ptr<MyClassImpl> m_pImpl;
};
  • pimpl.cpp
class MyClassImpl
{
public:
    void DoStuff() { /*...*/ }
    struct MyStructImpl {
      int a;
      int b;
    } variable_struct_impl;
};


// MyClass (External/User interface)
MyClass::MyClass () : m_pImpl(new MyClassImpl()) { }

MyClass::~MyClass () = default;

void MyClass::Foo() {
    m_pImpl->DoStuff();
}
  • How/What's the best practice to share a public member of the implementation to the Pimpl class (end user)?
    • What if they have a different name like in my example with struct MyStruct and struct MyStructImpl (variable_struct / variable_struct_impl)?

For methods, that's quite clear, we need to make the forward method anyway. (Foo() forwarded to DoStuff() in the example)


Solution

  • How to give access to public members with Pimpl?

    You don't. The point of PIMPL is to hide all members of the Private IMPLementation, and having public access to them is entirely contrary to that point.

    If you want pubic access, then don't put the member in a PIMPL.