C++ – Pimpl idiom vs Pure virtual class interface

abstract classcpimpl-idiom

I was wondering what would make a programmer to choose either Pimpl idiom or pure virtual class and inheritance.

I understand that pimpl idiom comes with one explicit extra indirection for each public method and the object creation overhead.

The Pure virtual class in the other hand comes with implicit indirection(vtable) for the inheriting implementation and I understand that no object creation overhead.
EDIT: But you'd need a factory if you create the object from the outside

What makes the pure virtual class less desirable than the pimpl idiom?

Best Answer

When writing a C++ class, it's appropriate to think about whether it's going to be

  1. A Value Type

    Copy by value, identity is never important. It's appropriate for it to be a key in a std::map. Example, a "string" class, or a "date" class, or a "complex number" class. To "copy" instances of such a class makes sense.

  2. An Entity type

    Identity is important. Always passed by reference, never by "value". Often, doesn't make sense to "copy" instances of the class at all. When it does make sense, a polymorphic "Clone" method is usually more appropriate. Examples: A Socket class, a Database class, a "policy" class, anything that would be a "closure" in a functional language.

Both pImpl and pure abstract base class are techniques to reduce compile time dependencies.

However, I only ever use pImpl to implement Value types (type 1), and only sometimes when I really want to minimize coupling and compile-time dependencies. Often, it's not worth the bother. As you rightly point out, there's more syntactic overhead because you have to write forwarding methods for all of the public methods. For type 2 classes, I always use a pure abstract base class with associated factory method(s).