What's is the point of PImpl pattern while we can use interface for same purpose in C++?

Posted by ZijingWu on Programmers See other posts from Programmers or by ZijingWu
Published on 2013-10-03T11:00:09Z Indexed on 2013/10/23 22:05 UTC
Read the original article Hit count: 153

I see a lot of source code which using PIMPL idiom in C++. I assume Its purposes are hidden the private data/type/implementation, so it can resolve dependence, and then reduce compile time and header include issue.

But interface class in C++ also have this capability, it can also used to hidden data/type and implementation. And to hidden let the caller just see the interface when create object, we can add an factory method in it declaration in interface header.

The comparison is:

  1. Cost:

    The interface way cost is lower, because you doesn't even need to repeat the public wrapper function implementation void Bar::doWork() { return m_impl->doWork(); }, you just need to define the signature in the interface.

  2. Well understand:

    The interface technology is more well understand by every C++ developer.

  3. Performance:

    Interface way performance not worse than PIMPL idiom, both an extra memory access. I assume the performance is same.

Following is the pseudocode code to illustrate my question:

// Forward declaration can help you avoid include BarImpl header, and those included in BarImpl header.
class BarImpl;
class Bar
{
public:
    // public functions
    void doWork();
private:
    // You doesn't need to compile Bar.cpp after change the implementation in BarImpl.cpp
    BarImpl* m_impl;
};

The same purpose can be implement using interface:

// Bar.h
class IBar
{
public:
    virtual ~IBar(){}
    // public functions
    virtual void doWork() = 0;
};

// to only expose the interface instead of class name to caller
IBar* createObject();

So what's the point of PIMPL?

© Programmers or respective owner

Related posts about design-patterns

Related posts about implementations