1

Possible Duplicate:
Pimpl idiom vs Pure virtual class interface

In hiding implementation, I've read a lot about the "proxy class" or "handle class" or "cheshire cat smile" technique where you essentially include a pointer to your "real" class as a data member in your public/proxy class, and then implement everything in the "real" class.

But I was looking at some sample code and noticed another technique that seems to be easier, as it doesn't require you to also write the "dummy" methods in the handle class to then call the real methods in the handle class, nor does it require any data members at all, and overall just seems more streamlined.

The technique is to simply define all your public methods as a struct (or a class where everything is public) and all virtual=0 member functions with nothing more. Thus there is no implementation. Then, define a static function that returns a pointer to this struct so the client can use the class. But behind the scenes this method actually returns a subclass of the struct, where you can then have much more going on inside this subclass.

If this is so straightforward and I would argue is more elegant than a public class including a data member that is a pointer to a separate class, and having to implement the public class's calls to the data member's methods, then why isn't this the technique most discussed in hiding implementation?

Community
  • 1
  • 1
johnbakers
  • 22,776
  • 20
  • 106
  • 230

1 Answers1

0

As noted on this article:

The reason why most people recommend the PIMPL approach is that it has some distinct advantages:

  • Factory functions are not needed, you can use new(), delete() or create objects on the stack.
  • You can subclass easily.
  • The interface methods are not virtual, so calling them might be faster. (On the other hand, we need an extra memory fetch to get to the implementation object.)
  • PIMPL can be introduced in an existing class without changing its external interface or its relation to other classes.

The abstract class method has some advantages of its own:

  • Cleaner code and a lot less typing, since we don't have to write forwarding stubs for the methods in the public interface.
  • Multiple classes can implement the same interface. We can statically or dynamically select which particular implementation we want to use, which gives us more flexibility.
johnbakers
  • 22,776
  • 20
  • 106
  • 230