1

I am trying to define interfaces for a library which will be using pimpl-idiom. Following is a typical interface class which I define.

struct A {
public:
   void func1();
   void func2();
   virtual void notif1();
   virtual void notif2();
private:
   class AImpl;
   AImpl *impl;
}

The functions func1(), func2() are the interface functions. And notif1(), notif2() are the notification functions which the application has to implement (in the subclass of A).

Is this the right way to define an interface for a library? Are there any disadvantages with this method or is there any better solution?


Thanks for all the answers. So from all the answers I gather that the following is a good way of representing an interface for a library.

// Forward declaration
class AImpl;

struct A {
public:
   void func1();
   void func2();
private:
   virtual void notif1();
   virtual void notif2();
   AImpl *impl;
}

The interface library will implement the interface functions and application will implement the notification functions in the derived class. Is there any good example of a library which follows this pattern?

user761867
  • 103
  • 1
  • 5
  • Unrelated to pimpls (i.e., to your actual question), but public virtual functions are a bad idea. Herb Sutter covers this multiple times in detail in his 'Exceptional C++' book series. – ildjarn May 19 '11 at 23:36

2 Answers2

3
  • The pimpl means your class can no longer be header-only. That means for users of the library it's no longer enough to #include your header but they must also link against the library's object code.
  • The runtime performance of the class in the header will be slightly slower, because it needs to dereference a pointer for every access of an opaque member. In exchange the idiom allows you to change opaque members of the class more often. But that's not much of an advantage for a library in production, because then it shouldn't change much anyway.

I don't think it's a good idea.

wilhelmtell
  • 53,297
  • 19
  • 89
  • 128
  • [Here](http://stackoverflow.com/questions/825018/pimpl-idiom-vs-pure-virtual-class-interface) is a good post about using PIMPL vs declaring pure virtual classes – user258808 May 19 '11 at 23:34
1

You are not required to declare the AImpl class inside struct A.

I generally do a forward declaraion:

//Forward Declaraion.
class AImpl;

struct A {
public:
   void func1();
   void func2();
   virtual void notif1();
   virtual void notif2();
private:
   AImpl *impl;
}
user258808
  • 744
  • 4
  • 5