Wednesday, March 30, 2011

Understanding C++ Pimpl Idiom

In C++, whenever a header file changes, any files that include that header file will need to be recompiled. To avoid such an issue, we can use pimpl (pointer to implementation) idiom.

Hello.h
#ifndef HELLO_H_
#define HELLO_H_

#include <boost/shared_ptr.hpp>

class HelloImpl; // forward declare this

class Hello {
public:
    Hello();
    virtual ~Hello();
    void sayHello() const;
private:
    boost::shared_ptr<HelloImpl> impl;
};

#endif /* HELLO_H_ */

Hello.cpp
#include "Hello.h"
#include <iostream>
using namespace std;

class HelloImpl {
public:
    void sayHello() const {
        cout << "Hello World" << endl;
    }
};

Hello::Hello() : impl(new HelloImpl) {
}

Hello::~Hello() {
}

void Hello::sayHello() const {
    impl->sayHello();
}

In this example, the use of smart pointer, such as Boost shared_ptr is recommended to avoid the hassle of writing the copy constructor, assignment operator, and destructor. With this approach, whenever the implementation changes, the client is insulated from the changes.

No comments:

Post a Comment