Search code examples
c++delegationpimpl-idiom

What patterns do you use to decouple interfaces and implementation in C++?


One problem in large C++ projects can be build times. There is some class high up in your dependency tree which you would need to work on, but usually you avoid doing so because every build takes a very long time. You don't necessarily want to change its public interface, but maybe you want to change its private members (add a cache-variable, extract a private method, ...). The problem you are facing is that in C++, even private members are declared in the public header file, so your build system needs to recompile everything.

What do you do in this situation?

I have sketched two solutions which I know of, but they both have their downsides, and maybe there is a better one I have not yet thought of.


Solution

  • The pimpl pattern:

    In your header file, only declare the public methods and a private pointer (the pimpl-pointer or delegate) to a forward declared implementation class.

    In your source, declare the implementation class, forward every public method of your public class to the delegate, and construct an instance of your pimpl class in every constructor of your public class.

    Plus:

    • Allows you to change the implementation of your class without having to recompile everything.
    • Inheritance works well, only the syntax becomes a little different.

    Minus:

    • Lots and lots of stupid method bodies to write to do the delegation.
    • Kind of awkward to debug since you have tons of delegates to step through.
    • An extra pointer in your base class, which might be an issue if you have lots of small objects.